首页 > 代码库 > Plus One Leetcode

Plus One Leetcode

Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.

You may assume the integer do not contain any leading zero, except the number 0 itself.

The digits are stored such that the most significant digit is at the head of the list.

 

这道题我是用了通用解法,忽略了本题的特殊性。其实如果加1的话,只是遇到9会进一位,剩下都不会有影响。

这个是我之前的解法:

public class Solution {
    public int[] plusOne(int[] digits) {
        if (digits == null) {
            return null;
        }
        List<Integer> num = new ArrayList<>();
        int carry = 0;
        for (int i = digits.length - 1; i >= 0; i--) {
            if (i == digits.length - 1) {
                int sum = (digits[i] + 1) % 10;
                carry = (digits[i] + 1) / 10;
                num.add(sum);
            } else {
                int sum = (digits[i] + carry) % 10;
                carry = (digits[i] + carry) / 10;
                num.add(sum);
            }
        }
        if (carry == 1) {
            num.add(carry);
        }
        int[] res = new int[num.size()];
        for (int i = num.size() - 1, j = 0; i >= 0; i--, j++) {
            res[j] = num.get(i);
        }
        return res;
    }
}

但是其实有更简洁的写法。。。

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

这个解法很巧妙,更巧妙的是如果跳出loop还没有结束,那么只需要重新建个数组把第一位改成1就可以了。

Plus One Leetcode