Link: https://oj.leetcode.com/problems/plus-one/
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.
我的代码:一次过。可以不用再写。Time: O(n), Space: O(1), worst case (all digits = 9): O(n)
public class Solution {
public int[] plusOne(int[] digits) {
int n = digits.length;
int[] result = new int[n];
if(digits[n-1] != 9){
digits[n-1] += 1;
return digits;
}
int i = n-1;
while(i>0 && digits[i] == 9){
digits[i] = 0;
i--;
}
if(digits[i] != 9){
digits[i] +=1;
}
else{
result = new int[n+1];
result[0] = 1;
return result;
}
return digits;
}
}
以上代码可以更简洁:
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;
}
//all digits = 9
int[] result = new int[n+1];
result[0] = 1;
return result;
}
}
Note: 我的Google 面试题@2014.2.