1 ms solution. Easy to understand


  • 0
    M
    public int[] plusOne(int[] digits) {
            
            int carry = 1;
            int[] result = new int[digits.length + 1];
            
            for (int i=digits.length - 1; i >= 0; i--) {
                int d = digits[i] + carry;
                digits[i] = d % 10;
                carry = d > 9 ? 1 : 0;
            }
            
            if (carry == 1) {
                System.arraycopy(digits, 0, result, 1, digits.length);
                result[0] = 1;
                return result;
            } else {
                return digits;
            }
            
        }
    

Log in to reply
 

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