給 vector 表示的數字 +1
Note:git
Example:code
Example 1: Input: [1,2,3] Output: [1,2,4] Explanation: The array represents the integer 123. Example 2: Input: [4,3,2,1] Output: [4,3,2,2] Explanation: The array represents the integer 4321.
class Solution { public: vector<int> plusOne(vector<int>& digits) { int n = digits.size(); for (int i = n - 1; i >= 0; i--) { if (digits[i] == 9) digits[i] = 0; else { digits[i] += 1; return digits; } } if (digits.front() == 0) { digits.insert(digits.begin(), 1); } return digits; } };
從最後開始檢查,是 9 就 變成 0, 再檢查前面的一位,直到不是 9 了,就直接加一而後返回,若是最前須要加位就加。ip