您的位置:首页 > 其它

leetcode--Plus One

2016-02-20 12:20 309 查看
题目:难度(Easy)

Given a non-negative number represented as an array of digits, plus one to the number.

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

Tags:Array Math

Similar Problems:(M) Multiply Strings (E) Add Binary

分析:用数组存数的各个数位,数组的靠前的位置数位越大,如[1,2,3]表示123,加1编程[1,2,4]

代码实现:

class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
digits.reverse()
#进行加1操作
digits[0]+=1
#update digits数组,divmod函数返回(商,余数)
for i in range(len(digits)-1):
carry, digits[i] = divmod(digits[i], 10)
digits[i+1] += carry
if digits[len(digits)-1] > 9:
digits[len(digits)-1] %= 10
digits.append(1)
digits.reverse()
return digits
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: