LeetCode 第 66 題 (Plus One)

liyuanbhu發表於2016-05-01

LeetCode 第 66 題 (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.

這道題屬於比較簡單的那種。只要模擬手算加法的過程就行了。下面是程式碼。

vector<int> plusOne(vector<int>& digits)
{
    int carry = 1;
    for(int i = digits.size() - 1; i > -1 ; i--)
    {
        int val = carry + digits[i];
        carry = (val) / 10;
        digits[i] = (val) % 10;
    }
    if(carry)
    {
        digits.insert (digits.begin(), carry);
    }
    return digits;
}

相關文章