66. Plus One

my solution

time: O(n)

space: O(n)

class Solution {
    public int[] plusOne(int[] digits) {
        int res[] = new int[digits.length+1];

        int plus = 1;
        for (int i = digits.length-1; i >= 0; i--) {
            digits[i] += plus;
            plus = digits[i]/10;
            digits[i] %= 10;
            res[i] = digits[i];
        }
        if (plus == 1) {
            res[0] = 1;
        }
        return plus == 1 ? res : digits;
    }
}

shorter one

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

Last updated