66. Plus One
Solution#
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
if (digits[digits.size() - 1] != 9) {
digits[digits.size() - 1]++;
return digits;
}
int carry = 1;
for (int i = digits.size() - 1; i >= 0; i--) {
digits[i] += carry;
carry = digits[i] / 10;
digits[i] = digits[i] % 10;
}
if (carry != 0) {
digits.insert(digits.begin(), carry);
}
return digits;
}
};
Complexity#
- Time Complexity: O(N), where N is the size of
digits
.
- Space Complexity: O(1), since we edit the original array.
All Solutions