public class Solution {
public int[] plusOne(int[] digits) {
int add = 1;
for(int i=digits.length-1; i>=0; i--){
int val = digits[i]+add;
digits[i] = val%10;
add = val/10;
}
if(add>0){
int[] result = new int[digits.length+1];
result[0]=add;
for(int i=1; i<result.length; i++){
result[i] = digits[i-1];
}
return result;
}
return digits;
}
}
分析:细节,就相当于在最后一位进1,然后处理前面的可能会发生变化的值。
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.