leetcode 66-Plus One(プラス1問題)

2490 ワード

問題の説明:
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 n=digits.size();
        digits[n-1] += 1;//(1) +1
        //int carry=0;
        for(int i=n-1;i>0;i--)
        {
            if(digits[i]>=10)
            {//(2) , 10, 
                digits[i-1] += digits[i]/10;
                digits[i] = digits[i]%10;
            }
        }
        //(3) 10
        if(digits[0]>=10)
        {// 10, 1 
            vector<int> d(n+1);
            d[0] = digits[0]/10;
            digits[0] %= 10;
            int k=1, j=0;
            while(j<n)
            {
                d[k++]=digits[j++];
            }
            return d;
        }
        return digits;
    }
};