题目:
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.
分析:
本题是将整数n的每一位存储在数组中,如n=9,则个位存入数组;n=98,个位和十位存入数组,且a[0]=9,a[1]=8,也就是最高位在数组初始位置,再执行加1操作。如果最高位需要进位,如n=99,a[0]=9,a[1]=9,加1后最高位会进位,这时候需要新建一个长度加1的数组。
代码:
public class plusOne {
public static int[] puls(int[] digits){
int flag=1;
int i=0;
for(i=digits.length-1;i>=0;i--){
digits[i]=digits[i]+flag;
if(digits[i]>9){
flag=1;
digits[i]=0;
}else{
return digits;
}
}
if(i==-1&&flag==1){
int[] newdigits=new int[digits.length+1];
newdigits[0]=1;
for(i=1;i<=digits.length;i++){
newdigits[i]=digits[i-1];
}
return newdigits;
}else{
return digits;
}
}
public static void main(String[] args){
int[] digits={9,9};
int[] result=puls(digits);
for(int i=0;i<result.length;i++){
System.out.println("i:"+i+",result:"+result[i]);
}
}
}