LeetCode(67)Plus One

871 ワード

タイトルは以下の通りです.
Given a non-negative number represented as an array of digits, plus one to the number. The digits are stored such that the most significant digit is at the head of the list.
テーマ分析:
簡単なテーマで、加算をシミュレートすればいいです.
マイコード:
class Solution {
public:
    vector<int> plusOne(vector<int> &digits) {
        int new_digit = 0;
        int over_flow = 0;
        vector<int> result;
        digits[digits.size() - 1] += 1;
        for (int i = digits.size() - 1; i >= 0; --i) {
            new_digit  = (over_flow + digits[i]) % 10;
            over_flow  = (over_flow + digits[i]) / 10;
            digits[i] = new_digit ;
        }
        result.assign(digits.begin(), digits.end());
        if (over_flow > 0)
            result.insert(result.begin(), 1);
        return result;
    }
};