首页 > 代码库 > Leetcode:Plus One

Leetcode:Plus One

戳我去解题

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.

 

分析:这题也是非常简单,就是简单模拟题

因为只有最末位加1,其余位没有额外加数,所以分情况:

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

 

后来看了他人的题解,有个小技巧,可以将 进位 carry 初始化为 加数,这样就可以统一代码,而不需要分情况了

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