1. 程式人生 > >66. Plus One(python+cpp)

66. Plus One(python+cpp)

題目:

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.

解釋:
把陣列看成是一個數字,返回這個數字+1後的結果,也用字串表示。
如果最後一位不是9,直接最後一位+1返回即可。
如果最後一位是9,要考慮進位的情況,找到最後一個不是9的數字,對其+1,其後歸0


這樣看來其實也不用考慮最後一位是不是9,只要找到最後一位不是9的那一位即可。
python程式碼:

class Solution:
    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        n=len(digits)
        i=n-1
        while(i>=0 and digits[i]==9):
            i-=1
        if i<0:
            return
[1]+[0]*n; else: digits[i]+=1 return digits[:i+1]+[0]*(n-1-i)

c++程式碼:

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        int n=digits.size();
        int i=n-1;
        while(i>=0 &&digits[i]==9)
            i--;
        vector<int>zeros(n-1-i,0);
        if (i<0)
        {
            zeros.insert(zeros.begin(),1); 
            return zeros;
        }
        else
        {
            digits[i]+=1;
            vector<int>new_digits(digits.begin(),digits.begin()+i+1);
            new_digits.insert(new_digits.end(),zeros.begin(),zeros.end());
            return new_digits;
        }      
    }
};

總結:
和大數加法還是不一樣的,剛開始做的時候直接把陣列轉換成string再轉換成int做的,這樣不僅速度慢而且很沒有意義。