Java solution with explaination


  • 0
    public class Solution {
        public int[] plusOne(int[] digits) {
            if (digits.length == 0) return digits;
            int i = digits.length - 1;
            // should we advance one to the next digit
            boolean isAdv;
            do {
                digits[i] = digits[i] + 1;
                int result = digits[i];
                // if the digit after plus one is 10, we set the +1 flag of next digit to true and set this digit to 0
                if (result == 10) {
                    isAdv = true;
                    digits[i] = 0;
                }
                else isAdv = false;
                i -= 1;
            } while(isAdv && i >= 0);
            // because using post while loop, check against -1
            // this is the case when evry digit in the array is 9
            if (i == -1 && isAdv) {
                int[] result = new int[digits.length+1];
                result[0] = 1;
                for(int j = 1; j < result.length; j++) {
                    result[j] = 0;
                }
                return result;
            }
            return digits;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.