66. Plus One

1174 ワード

class Solution {
    public int[] plusOne(int[] digits) {
        int l = digits.length - 1;
        if (digits[l] != 9) {
            digits[l]++;
            return digits;
        } else {
            while (l > 0 && digits[l - 1] == 9) {
                digits[l - 1] = 0;
                l--;
            }
        }
            
        if (l <= 0) {
            int[] ans = new int[digits.length + 1];
            ans[0] = 1;
            return ans; 
        }
        
        return digits; 
    }
}
class Solution {
    public int[] plusOne(int[] digits) {
        int l = digits.length - 1;
        for (int i = l; i >= 0; i--) {
            if (digits[i] < 9) {
                digits[i]++;
                return digits;
            }
            
            digits[i] = 0;
        } 
        
        digits = new int[l + 2];
        digits[0] = 1;
        
        return digits;
    }
}
Runtime: 0 ms, faster than 100.00% of Java online submissions for Plus One.
Memory Usage: 37.5 MB, less than 41.91% of Java online submissions for Plus One.