Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
思路:从数组的最后一位往前开始加1,需要考虑进位。如果到数组0位时仍有进位,新开一个长度为length + 1的数组。
方法一:
public class Solution {
public int[] plusOne(int[] digits) {
int c=1;
for(int i=(digits.length-1);i>=0;i--){
int a=digits[i]+c;
c=a/10;
digits[i]=a%10;
}
if(c==1){
int[] newDigits=new int[digits.length+1];
newDigits[0]=1;
for(int i=0;i<digits.length;i++){
newDigits[i+1]=digits[i];
}
return newDigits;
}
return digits;
}
}
方法二:对数组的每一位,如果值小于9,直接使该位的值加一,并返回当前数组;如果等于9,令该位为0;依次遍历到第0位后,如果还存在进位,则说明原数组的所有位都为9,直接返回一个新建的一个长度加1、首位为1的数组。
public class Solution {
public int[] plusOne(int[] digits) {
int n = digits.length;
for(int i=n-1; i>=0; i--) {
if(digits[i]<9) {
digits[i]++;
return digits;
}
digits[i] = 0;
}
int[] res = new int[n+1];
res[0] = 1;
return res;
}
}