Plus One Java Solution - The Coding Shala

Home >> Interview Questions >> Plus One

Plus One

Problem:
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

Approach: 

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--){
            if(digits[i]<9){
                digits[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.

Comments

Popular Posts from this Blog

Java Program to Convert Binary to Decimal - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

LeetCode - Shuffle the Array Solution - The Coding Shala

Java Program to Find GCD or HCF of Two Numbers - The Coding Shala