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.
class Solution {
public int[] plusOne(int[] digits) {
if(digits==null || digits.length<=0) return digits;
int i=digits.length-1;
while(i>=0 && digits[i]==9){
digits[i] = 0;
i--;
}
if(i<0){
int[] res = new int[digits.length+1];
res[0] = 1;
return res;
}
digits[i] = digits[i]+1;
return digits;
}
}
这里的关键点就是处理进位,数字的元素是高位在数组的开头,低位在数组的末尾,对数字进行加1,如果当前数组元素为9,则当前位置为0,产生进位,循环到某一位的元素小于9,在该位置的元素加1即可,如果真个数组所有的元素全部为9,则需要新建一个数组长度增1的数组