66. Plus One(第六週)
阿新 • • 發佈:2019-01-24
Description
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.
Input: "[0]"
Output:
"[1]"
Solution
一道關於vector
容器使用的簡單題目,題目要求是要做簡單的加一操作。在原來的用非空vector
表示的數字上加上1,返回得到的結果。
思路是這樣的,首先對最後一位的數字加一,如果它沒有變成兩位數,那麼,就這樣返回。然後就是特殊情況——如果它變成了10,那麼就要進行進位。進位的規則很簡單:就是把最後一位減去10,把它的前一位加上一,如果前面一位還是10,那麼就繼續迴圈。所以這個操作我們可以用while
迴圈來完成。
然後就是最特殊的情況,比如說1位數的9,加上1後前一位是空的,這時候我們就要用到vector
帶有的方法insert
來進行新增。
將上述兩個思路整合得到程式碼如下:
Source Code
submission
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
digits[digits.size() - 1] += 1;
int j = digits.size() - 1;
bool isNeedToAddOneDigit = false;
while(j > 0 && digits[j] >= 10)
{
digits[j] -= 10 ;
digits[j - 1] += 1;
j--;
}
if (digits[0] >= 10)
{
digits[0] -= 10;
digits.insert(digits.begin(), 1);
}
return digits;
}
};