Leetcode: Plus One

Given a non-negative number represented as an array of digits, plus one to the number.

The digits are stored such that the most significant digit is at the head of the list.

public class Solution {
    public int[] plusOne(int[] digits) {
        if(digits==null||digits.length==0){
            return digits;
        }
        int index = digits.length-1;
        int carry = 1;
        int sum;
        while(index>=0 && carry==1){
            sum = digits[index]+carry;
            digits[index] = sum%10;
            carry = sum/10;
            index--;
        }
        if(carry==1){
            int[] newDigits = new int[digits.length+1];
            newDigits[0]=carry;
            for(int i=0;i<digits.length;i++){
                newDigits[i+1] = digits[i];
            }
            return newDigits;
        }
        return digits;
        
    }
}

Note: use a while loop here so that we don’t need to go through the entire array if it’s not necessary. It starts from the last index of the array and go backwards. If carry==1, then it will keep going, otherwise it will stop. After the traversing is done, it checks if the first digit==0 and handle that case.

FacebookTwitterGoogle+Share

Leave a Reply

Your email address will not be published. Required fields are marked *