[leedcode 66] Plus One
2555 ワード
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.
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) {
// , carry
//carry 1, 1, , ,
// : , resize
int len=digits.length;
//if(len<1) return digits;
int carry=1;
for(int i=len-1;i>=0;i--){
int temp=digits[i]+carry;
digits[i]=temp%10;
carry=temp/10;
}
if(carry>0){
int[] newdigits=new int[len+1];
for(int i=1;i<len+1;i++){
newdigits[i]=digits[i-1];
}
newdigits[0]=carry;
return newdigits;
}else return digits;
}
}