LeetCode題目之66

題目描述如下:

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

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.

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.

個人思路簡述:

       這個題目是大數加法的簡單版本,因爲大數加法需要考慮的不止是加一,還需要考慮負數。

       具體做法就是從容器的末端開始遍歷,給當前數字加一。由於只是加一操作,如果該數變成兩位數的話,他只能是10,所以加一操作之後判斷該數是否等於10。如果等於10的話則把當前數置0然後繼續循環,給該數的前一位執行加一操作,方法同上。

       用這種方法的話需要考慮到特殊情況,當我們的輸入爲9或者99或者999這種數的時候,整個大數字的長度會加一,因此我們在跳出循環之後再加一個判斷,既看最前面的一個數是不是等於0,如果等於0的話,就在最前面插入一個1就搞定了。

       例如,我們輸入是[9],按照上述思路執行完循環體之後是[0],所以我們再插入一個1之後就變成了[1,0],這樣就是正確的結果了。

代碼片段:

vector<int> plusOne(vector<int>& digits) {
        for(int i = digits.size() - 1; i >= 0; --i){
            digits[i] += 1;//遍歷執行+1操作
            if(digits[i] == 10) digits[i] = 0;//判斷是否需要向前進位
            else break;
        }
        if(digits[0] == 0) digits.insert(digits.begin(),1);//判斷是否最高位仍需進位
        return digits;
    }

 

發佈了9 篇原創文章 · 獲贊 0 · 訪問量 6937
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章