Question
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.
思路
实质是用数组实现了大数加法,从最后一位加1开始,设置进位,如到数组头时仍有进位则将数组按位后移,0位补上进位。
代码
public class Solution {
public int[] plusOne(int[] digits) {
int[] result = new int[digits.length + 1];
int c = 1;//进位
for(int i = digits.length - 1;i >= 0;i--){
int and = digits[i] + c;
int low = and%10;
c = and/10;
digits[i] = low;
}
if(c != 0){
result[0] = c;
for(int i = 0;i < digits.length;i++){
result[i + 1] = digits[i];
}
return result;
}
else
return digits;
}
}
结果及分析
【You are here!
Your runtime beats 5.29% of javasubmissions.】时间复杂度为O(n+1),空间复杂度为O(n+1);
二刷THOUHGT II
其实没必要从头加到尾,只有在都是9的情况下才会发生这种情况。从尾开始遍历,若遍历的元素小于9,则加一返回数组就可以了。若等于9,则将其置为0.如果遍历完还没有返回,说明没有遇到小于9的情况。所以要新建一个数组,并将其开头置为1,不用把原数组中的数字导入,因为他们都是0.
CODE
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;
}
else
digits[i] = 0;
}
int[] arr = new int[n + 1];
arr[0] = 1;
return arr;
}
}
RESULT
time complexity is O(n),space complexity is O(N);