题目:
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.
题解:C++版:
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int i = digits.size() - 1;
while(i >= 0) {
int result = digits[i] + 1;
digits[i] = result % 10;
if(result < 10)
return digits;
i--;
}
digits.insert(digits.begin(), 1);
return digits;
}
};
Java版:
public class Solution {
public int[] plusOne(int[] digits) {
int i = digits.length - 1;
while(i >= 0) {
int result = digits[i] + 1;
digits[i] = result % 10;
if(result < 10)
return digits;
i--;
}
int[] newResult = new int[digits.length + 1];
newResult[0] = 1;
for(int j = 0; j < digits.length; j++) {
newResult[j + 1] = digits[j];
}
return newResult;
}
}
Python版:
class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
carry = 1
for i in range(len(digits) - 1, -1, -1):
result = digits[i] + carry
digits[i] = result % 10
if result < 10:
return digits
return [1] + digits