Given a number represented as an array of digits, plus one to the number.
例如[7,8,9]+1=[7,9,0]
[8,9,9,9]+1=[9,0,0,0]
[9,9,9,9]+1 = [1,0,0,0,0]
思路:从最后一位按位加几颗,注意进位。如果没有进位的话也就不需要再向前扫描了,毕竟只是+1而已。
public class Solution {
public int[] plusOne(int[] digits) {
int add = 1;
for(int i=digits.length-1;i>=0;i--){
int temp = add;
add = (digits[i]+add)/10;
digits[i] = (digits[i]+temp)%10;
if(add==0) break;
}
if(add!=0){
int[] result = new int[digits.length+1];
for(int i=0;i<digits.length;i++){
result[i+1] = digits[i];
}
result[0] = 1;
return result;
}else{
return digits;
}
}
}