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.
FAILED APPROACH:

 class Solution {
    public int[] plusOne(int[] digits) {
        digits[digits.length-1]+=1;
        return digits;
    }
}


Above code seems to be correct, the mistake occurs when at end contains 9
     Input        Output   Output according to our code
i.e., [9]      -  [1, 0]    -    [10]
       [9, 9]  - [1, 0, 0] -    [9, 10]
Thus above code is not a solution for this problem.

SUCCESSFULL APPROACH

 class Solution {
    public int[] plusOne(int[] digits) {
         int length= digits.length;
        for(int i=length-1;i>=0;i--){
            if(digits[i]<9){
                digits[i]++;
                return digits;
            }
            digits[i]=0;
        }
       
        int[] tmp = new int[length+1];
        tmp[0]=1;
        return tmp;
    }
}


Above code overcomes all mistakes done in previous approach.

1) Here we are going to iterate from end, because we need to increment plus one at end.
2) If any digit is less than 9, increment by 1 and return that place itself.
3) If last digit is 9, then add 0 at that position and increment 1 to previous and return.
4) Comment optional is for below case., [9, 9, 9]. For these type of inputs, create a new array with one extra length. And add finally 1 to array[0].

Related Post:

Click here for April month challenges with solution and explanation

Click Follow button to receive latest updates from us instantly.

Please let us know about your views in comment section.

Help Others, Please Share..!!!!

                                                     😍..Happy Coding...😍

Comments

Popular posts from this blog

First Unique Character in a String

Balanced Binary Tree

Majority Element

Sequential Digits