Given a non-empty array of digits representing a non-negative integer, plus 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 contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example 1:
Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Example 2:
Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
用一个数组代表一个数字,让用数组输出这个数字+1后的结果
思路:
按正常的从右至左做加法,同时加上进位
需要注意的是在最左边有进位的时候因为原有的数组长度不够,需要分配一个新的数组
**注意不能用digits[i] = (digits[i] + plus) % 10,然后再plus = (digits[i] + plus) /10
因为前面的操作下digits[i]已经更新,后面再用更新后的digits[i]就会出错,所以用sum变量来保存相加的和
//0ms
public int[] plusOne(int[] digits) {
int plus = 0;
int len = digits.length;
int sum = 0;
sum = digits[len - 1] + 1 + plus;
digits[len - 1] = sum % 10;
plus = sum / 10;
for (int i = len - 2; i >= 0; i--) {
sum = digits[i] + plus;
digits[i] = sum % 10;
plus = sum / 10;
}
if (plus > 0) {
int[] result = new int[len + 1];
for (int i = len - 1; i >= 0; i--) {
result[i + 1] = digits[i];
}
result[0] = plus;
return result;
}
return digits;
}
博客围绕用数组表示数字并输出该数字加1后的结果展开。介绍了按从右至左做加法并处理进位的思路,还指出在最左边有进位时需分配新数组,同时强调不能直接更新数组元素,要用sum变量保存相加和,避免计算出错。
569

被折叠的 条评论
为什么被折叠?



