其他分享
首页 > 其他分享> > 66. Plus One

66. Plus One

作者:互联网

My first solution:

class Solution {
    public int[] plusOne(int[] digits) {
        int n = digits.length;
        int carry = 1;
        for(int i=n-1;i>=0;i--){
            int digit = digits[i];
            int sum = digit+carry;
            if(sum/10==0){
                digits[i]=sum;
                return digits;
            }else{
                digits[i]=sum%10;
                carry = sum/10;
            }
        }
        if(carry>0){
            int[] res = new int[n+1];
            res[0]=carry;
            for(int i=1;i<n+1;i++){
                res[i]=digits[i-1];
            }
            return res;
        }
        return digits;
    }
}

The smarter solution and shorter solution:

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

 

标签:digits,10,int,sum,solution,Plus,66,carry
来源: https://www.cnblogs.com/feiflytech/p/16080044.html