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.
Hide Company Tags
一刷
题解:
Time Complexity - O(n), Space Complexity - O(n)。
public class Solution {
public int[] plusOne(int[] digits) {
int added = 1;
for(int i=digits.length-1; i>=0; i--){
int cur = digits[i] + added;
added = cur/10;
cur = cur%10;
digits[i] = cur;
}
if(added == 1){
int[] temp = new int [digits.length + 1];
temp[0] = 1;
for(int i=0; i<digits.length; i++){
temp[i+1] = digits[i];
}
return temp;
}
else return digits;
}
}
还有一种简洁的方法:
public class Solution {
public int[] plusOne(int[] digits) {
int i = digits.length -1;
while(i>=0){
if(digits[i] == 9){
digits[i] = 0;
i--;
}
else {
digits[i] +=1;
return digits;
}
}
int[] temp = new int [digits.length+1];
temp[0] = 1;
return temp;
}
}