2020年5月23日 星期六

LeetCode 66. Plus One [Easy] [C++] 解題筆記

這題給我們一個 "non-empty" array,表示一個數字,最左邊表示最高位,最右邊表示最低位,並保證最高位不會是 0,要求將這個 array 表示的數字加一後返回。

EX:

    [1,2,3] represent 123.
Ans: [1,2,4], represent 124.

想法:
    這題基本上就是照著小學學的加減法照著做而已,沒啥特別的,注意進位問題!

完整程式碼:

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        int carry = 1;
        for (int i = digits.size() - 1; i >= 0; i--) {
            if (carry == 0) { return digits; }
            int sum = digits[i] + carry;
            digits[i] = sum % 10;
            carry = sum / 10;
        }
        if (carry > 0) {
            digits.insert(digits.begin(), carry);
        }
        return digits;
    }
};


沒有留言:

張貼留言