[LeetCode]Plus One

 

由于忙着作实验写paper,刷题的进度放慢了一点。爬上来更新一下最近作的几道题目。git

Given a number represented as an array of digits, plus one to the number.数组

模拟问题。给定输入是一个vector数组,输出加1后的计算结果。ide

将进位carry初始值置为1,从数组的最后一位开始加,注意最高位的进位。spa

class Solution {
public:
    vector<int> plusOne(vector<int> &digits) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        vector<int> ret;
        int n = digits.size();
        
        int carry = 1;
        const int BASE = 10;
        for(int i=n-1; i>=0; --i)
        {
            int tmp = digits[i]+carry;
            ret.insert(ret.begin(), tmp%BASE);
            carry = tmp>=BASE?1:0; //
        }
        // final carry bit
        if(carry)
            ret.insert(ret.begin(), carry);
        return ret;
    }
};
View Code
相关文章
相关标签/搜索