+1

问题给定一个有由数字构成的数组表示的数,求该数加1的结果。
public class Solution {
    public int[] plusOne(int[] digits) {
    }
}

很简单的问题,但是一遍写通过,还是要求基本功比较扎实。注意进位的处理。
Input                       Output

[0]

[1]

[1]

[2]

[9]

[1,0]

[1,0]

[1,1]

[9,9]

[1,0,0]

[1,2,3]

[1,2,4]

[9,9,9]

[1,0,0,0]

[8,9,9,9]

[9,0,0,0]

[1,0,0,0,0]

[1,0,0,0,1]

[9,8,7,6,5,4,3,2,1,0]

[9,8,7,6,5,4,3,2,1,1]


代码如下:

public  class Solution {
     public  int[] plusOne( int[] digits) {
         int extra = 1;
         for( int i=digits.length-1;i>=0;--i){
             int t = digits[i]+extra;
             if(t>=10){
                extra = 1;
                digits[i] = t-10;
            }
             else  if(extra!=0){
                extra = 0;
                digits[i] = t;
                break;
            }
        }
         if(extra>0){
             int[] newDigits =  new  int[digits.length+1];
            newDigits[0] = extra;
            System.arraycopy(digits,0,newDigits,1,digits.length);
             return newDigits;
        }
         return  digits;
    }
}



你可能感兴趣的:(+1)