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,因?yàn)闆]有進(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)