【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.

思路:

從最後一位開始讀,每位加一查看是否有超位。超位進位,最後如果沒有位可進了在vetor首位插入新元素。

代碼:

class Solution {
public:
    vector<int> plusOne(vector<int> &digits) {
        int carry = 0;
        vector<int> res;
        int  i;

        for ( i = digits.size()-1; i>=0; i-- ){
            digits[i] = 1+carry+digits[i];
            carry = digits[i]/10;
            digits[i] %= 10;
        }
        if(carry) digits.insert(digits.begin(),1);
        return res;
    }
};

這個的問題是1. return的res最終都沒有值,因爲過程中沒有給它賦值。2. 邏輯錯誤,是最後一位加一並不是每一位都加一!

更改代碼:

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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章