11 lines Java solution


  • 0

    Be careful when we have, say 99, we will need to create a new array to put 100. We only need to assign "1" to the first element since the default values of the remaining elements are "0".

    public class Solution {
        public int[] plusOne(int[] digits) {
            for(int i = digits.length - 1; i >= 0; i--) {
                digits[i] = (digits[i] + 1 != 10) ? digits[i] + 1 : 0;
                if(digits[i] != 0) return digits;
            }
            int [] result = new int[digits.length + 1];
            result[0] = 1;
            return result;
        }
    }
    

Log in to reply
 

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