LeetCode作題筆記 - 66 - 加一(簡單)

題目:加一(難度:簡單)

Given a non-empty array of digits representing a non-negative integer, plus one to the integer.git

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.數組

You may assume the integer does not contain any leading zero, except the number 0 itself.spa

Example 1:

Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

Example 2:

Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.

思路

根據加法原理,加1加在最低位(個位)上。若是不進位,則只需將最低位加1。若是進位,則說明最低位是9,那麼加上1後,最低位爲0,而後考慮高一位(十位)的狀況。若是高一位不進位,那麼加1後結束,若是進位則必然本來是9,進位後變爲0,繼續向高一位進位。 所以,只須要從最低位開始,向高位遍歷,若是不發生進位,則能夠直接結束。 可是,若是一直到最高位,仍然有進位,怎麼辦?應該是最高位變0,並新增更高的一位,且爲1。考慮到是vector,若是要在最開頭加上一個元素,則須要消耗O(n)時間,確定儘可能避免這樣的操做。仔細回想,對任意一位來講,只有本來是9的狀況下,纔可能出現進位。所以,若是到最高位仍然須要進位,則說明本來的每一位都是9,而加1後,每一位都變爲了0,只有多出來的最高位是1。因此,對這種特殊狀況,只須要將數組的第一個元素設爲1,而後最後添加一個0便可,只須要消耗O(1)時間。code

代碼

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        auto it = digits.end()-1;
        *it = (*it)+1; // 最低位加1
        for (; it > digits.begin(); --it) // 從後向前遍歷
        {
            if (*it == 10) // 須要進位
            {
                *it = 0;
                *(it-1) += 1;
            }
            else // 不進位,直接結束
            {
                return digits;
            }
        }
        if (*it == 10) // 最高位進1,說明本來全部位都是9
        {
            // 最高位置1,最後添0
            *it = 1;
            digits.push_back(0);
        }
        return digits;
    }
};
相關文章
相關標籤/搜索