Plus One Java Solution - The Coding Shala

Home >> Interview Questions >> Plus One

Plus One

Given a non-empty array of digits representing a non-negative integer, plus one to the integer.

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

Example 1:

Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

Example 2:

Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.

Plus One Java Solution


Here the simple idea is if the number in the array is less than 9 then we don't have to forward carry 1 to the next number. 

if all the numbers are 9 in the array then we have to add 1 at the beginning of the array[need to create new array].

java Code:: 

class Solution {
    public int[] plusOne(int[] digits) {
        int len = digits.length;
        for(int i = len-1; i>=0; i--){
                return digits;
            digits[i] = 0;
        int[] ans = new int[len+1]; // if all the numbers are 9
        ans[0] = 1;
        return ans;

Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.


Popular Posts from this Blog

LeetCode - Crawler Log Folder Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala

First Unique Character in a String Java - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

Add two numbers in Scala - The Coding Shala