LeetCode.66.Plus One

原題鏈接:Plus One

題目內容:Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.

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

The digits are stored such that the most significant digit is at the head of the list.

要求:對一個數組化的數字進行加一操作,大數計算思路,注意全爲9的時候特殊情況


C++

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        for (int i=digits.size()-1; i>=0; i--){
            if (digits[i] == 9){
                digits[i] = 0;
            }
            else {
                digits[i] ++;
                return digits;
            }
        }
        digits[0] = 1;
        digits.push_back(0);
        return digits;
    }
};

Python

class Solution(object):
    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        for i in range(len(digits)-1, -1, -1):
            if digits[i] == 9:
                digits[i] = 0
            else:
                digits[i] += 1
                return digits
        digits.insert(0, 1)
        return digits

注意:python下的range如果使用倒序,需要第三個參數爲-1;
range(5, -1, -1) = range(0, 6, 1)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章