難度:easy
題目描述
Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
算法分析
(1)尾部+1
(2)尾部加1後沒有進位,直接得到結果
(3)循環進位,for循環實現
(4)首位特殊處理,如果首位需要進位,需要重新聲明一個vector用於存儲結果
代碼實現
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int n = digits.size();
digits[n - 1] += 1;
// 沒有進位
if (digits[n - 1] < 10) return digits;
for (int i = n - 2; i >= 0; --i) {
digits[i] += digits[i + 1] / 10;
digits[i + 1] %= 10;
}
// 首位沒有出現進位
if (digits[0] < 10) return digits;
// 首位需要進位
vector<int> result;
result.push_back(1);
digits[0] %= 10;
for (int i = 0; i < n; ++i) {
result.push_back(digits[i]);
}
return result;
}
};