0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

LeetCode: 66. Plus One

Last updated at Posted at 2019-12-20

問題の要約

数値の一桁づつが要素として格納された配列に対し、1を足し算する問題

問題

問題へのリンク

回答 その1

愚直に一桁づつ繰上げて計算しました。

class Solution {
    void carryUp(vector<int>::iterator curDigit, int* nextDigit) {
            *curDigit = *curDigit + *nextDigit;
            
            if(*curDigit>9) {
                *nextDigit=1;
                *curDigit = *curDigit - 10;
            } else
                *nextDigit=0;
    }
public:
    vector<int> plusOne(vector<int>& digits) {
        vector<int>::iterator curDigit=digits.end()-1;
        (*curDigit)++;
        int nextDigit=0;
        
        for(;curDigit!=digits.begin();curDigit--) {
            carryUp(curDigit,&nextDigit);
        }
        
        carryUp(curDigit,&nextDigit);
        
        if(nextDigit==1)
            curDigit=digits.insert(curDigit,1);
        
        return digits;
    }
};
時間計算量:O(N)、空間計算量:O(1)

愚直に繰り上げ計算したので、スマートではないと思ったけど、提出したら Runtime=4 ms、Memory=8.7 MB 。そこそこ良い結果でした。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?