66. Plus One
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;
}Last updated