[LeetCode][Python]66. 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.

思路:一開始沒看懂題目的意思,后來才明白是用一個列表代表一個非負(fù)整數(shù),然后在最后一位加一,求新返回的列表。需要考慮的是空列表,列表最后一位小于9,最后一位等于9等情況。

要設(shè)置一個進(jìn)位,初始值為1,從最后一個元素循環(huán),依次給列表元素加一,如果最后的元素小于等于9,就直接返回加一后的list,因為沒有進(jìn)位。如果有進(jìn)位,則置位0。最后在列表的第一個位置插入1。

#!usr/bin/env  
# -*-coding:utf-8 -*-
class Solution(object):
    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        if len(digits) == 0:
            return [1]
        carry = 1
        for i in xrange(len(digits)-1, -1, -1):
            digits[i] += carry
            if digits[i] <= 9:
                return digits
            else:
                digits[i] = 0

        digits.insert(0, 1)
        return digits

if __name__ == '__main__':
    sol = Solution()
    digits = [2, 1, 9, 9]
    print sol.plusOne(digits)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗。 張土汪:刷leetcod...
    土汪閱讀 12,775評論 0 33
  • 問題描述: 對用數(shù)組表示的數(shù)字進(jìn)行加一操作 示例:輸入:[9,9] 輸出:[1,0,0]輸入...
    小歪與大白兔閱讀 133評論 0 0
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,973評論 19 139
  • Given a non-negative integer represented as a non-empty a...
    ShutLove閱讀 251評論 0 0
  • 早晨,天氣陰轉(zhuǎn)多云,心情也是,思維跳躍性太高,有些許的不高興,飲食也無一例外,可是我只是想做一顆勇敢的平凡的豆子...
    喬思麻麻閱讀 235評論 0 0