題目
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.
解
public class Solution {
public int[] plusOne(int[] digits) {
int j=digits.length-1;
digits[j]+=1;
while(j>0){
if(digits[j]>9){
digits[j]=digits[j]-10;
digits[j-1]+=1;
}
j--;
}
if(digits[0]<10){
return digits;
}else
{
int carry=0;
if(digits[0]>9){
digits[0]=digits[0]-10;
carry=1;
}
int[] ret=new int[digits.length+1];
ret[0]=carry;
for(int i=1;i<ret.length;i++){
ret[i]=digits[i-1];
}
return ret;
}
}
}