Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int n = size(digits) - 1;
if (digits[n] != 9) { // 末位不为 9,直接加 1 返回即可
++digits[n];
return digits;
}
while (digits[n] == 9) { // 末尾有多个 9,均改为 0
digits[n] = 0;
if (--n < 0) { // 如果全是 9,首位改为 1,末位加一个 0
digits[0] = 1;
digits.emplace_back(0);
return digits;
}
}
++digits[n]; // 多个 9 但不全是 9,最后一个 9 的下一位加 1
return digits;
}
};
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int carry = 1;
for (auto it = rbegin(digits); it != rend(digits); ++it) {
if (!carry) {
break;
}
*it += carry;
carry = *it / 10;
*it %= 10;
}
if (carry) {
digits.emplace(begin(digits), carry);
}
return digits;
}
};