Simple Java solution with comments


  • 0
    W
    public int[] plusOne(int[] digits) {
        if(digits == null || digits.length == 0)
            return new int[]{};
        int carry = 1;  //加1可以看成是有进位1
        for(int i = digits.length - 1; i >= 0; i--) {
            int sum = carry + digits[i];
            if(sum == 10) {
                carry = 1;
                digits[i] = 0;
            } else {
                digits[i] += 1;
                return digits;
            }
        }
        int[] result = new int[digits.length+1];    //比原有的digits多出一位
        result[0] = 1;
        return result;
    }

  • 0
    R

    There is no need setting

    carry = 1;
    

    in the

    if (sum == 10) {
        ......
    }
    

    block.


  • 0
    W

    @reggiezhou
    when the sum is 10, it should have carry=1.


  • 0
    R

    @WuQiFu You have already set carry = 1 before the for loop. So carry would remain 1 in the if(sum == 10) block without setting it to 1 again. You could try to run the code without this line.


  • 0
    W

    @reggiezhou
    You are right!


Log in to reply
 

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