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.
Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
// Naive Method
vector<int> plusOne(vector<int>& digits) { // time: O(n); space: O(n)
int n = digits.size();
vector<int> res(digits.begin(), digits.end());
int carry = 1;
for (int i = n - 1; i >= 0; --i) {
res[i] += carry;
carry = res[i] / 10;
res[i] %= 10;
}
if (carry) res.insert(res.begin(), carry);
return res;
}
vector<int> plusOne(vector<int>& digits) { // time: O(n); space: O(1)
int n = digits.size();
for (int i = n - 1; i >= 0; --i) {
if (digits[i] == 9) {
digits[i] = 0;
} else {
++digits[i];
return digits;
}
}
digits[0] = 1;
digits.push_back(0);
return digits;
}