题目:
Given a non-empty array of decimal digits representing a non-negative integer, increment one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
思路:
一开始的想法是将digits恢复成十进制的数,完成+1操作后,再借助String类的String.valueOf()方法将其转换为String类型,从而求出长度,再放回到数组中,思路可行,但提交后发现digits的长度在0和100之间,int及long都无法满足,遂放弃该方法,改用以下方法,由于每次只加一,所以如果digits[0]=0时,一定产生进位1,同时剩下数组数值为0。
class Solution {
public int[] plusOne(int[] digits) {
int n = digits.length;
if(digits[n-1] != 9) {
digits[n-1]++;
return digits;
}
else {
int carry = 1;
int sum = 0;
digits[n-1] = 0;
for(int j = n-2; j >= 0 ;j--) {
sum = carry + digits[j];
digits[j] = sum % 10;
carry = sum / 10;
}
if(digits[0]==0) {
int[] result = new int[n+1];
result[0]=1;
return result;
}
return digits;
}
}
}