66. Plus One
Given a non-negative number represented as an array of digits, plus one to the number.
The digits are stored such that the most significant digit is at the head of the list.
题目:数字用数组表示,然后+1;
提示:
从数组最后一位开始循环,如果数字<9,那么就+1,并且返回数组;
如果最后一位=9,那么+1之后需要进位,则把这一位置为0;
如果最高位需要进位,那么new一个新数组,将第一位置为1,其余的让系统自动初始化为0;
public class Solution {
public int[] plusOne(int[] digits) {
if(digits==null||digits.length<=0){
return null;
}
int n=digits.length;
for(int i=n-1;i>=0;i--){
if(digits[i]<9){
digits[i]++;
return digits;
}
digits[i]=0;
}
int []newDigits=new int[n+1];
newDigits[0]=1;
return newDigits;
}
}