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)