【LeetCode】66. Plus One

时间:2023-08-04 19:17:50

题目:

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.

提示:

此题其实是模拟我们在小学时候学习的加法进位的操作。难度不大。

代码:

空间复杂度是O(n)的方法:

class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int size = digits.size() - ;
digits[size] += ;
if (digits[size] < ) {
return digits;
}
vector<int> result;
for (int i = size; i > ; --i) {
if (digits[i] == ) {
digits[i] = ;
digits[i-] += ;
}
}
if (digits[] == ) {
result.push_back();
digits[] = ;
}
for (int i = ; i <= size; ++i) {
result.push_back(digits[i]);
}
return result;
}
};

空间复杂度是O(1)的方法:

class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
for (int i = digits.size(); i--; digits[i] = )
if (digits[i]++ < ) return digits;
digits[] = ;
digits.push_back();
return digits;
}
};