【题目】
Given a non-negative integer represented asa non-empty array of digits, plus one to the integer.
You may assume the integer do not containany leading zero, except the number 0 itself.
The digits are stored such that the mostsignificant digit is at the head of the list.
给定一个数组,将数加一,返回新的数组。比如[9,9],返回[1,0,0]。
【思路】
数组末尾位加1,然后如果进位就向前一个数字加1.
【Python实现】
classSolution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
digits_length = len(digits)
if digits_length == 0:
return [1]
carry = 0#进位
digits[digits_length - 1] += 1#末尾加1
while digits_length > 0:
digits[digits_length - 1] += carry
if digits[digits_length - 1] >= 10:
digits[digits_length - 1], carry= digits[digits_length - 1] % 10, digits[digits_length - 1] // 10
else:
carry = 0
break
digits_length -= 1
if carry == 0:
print(digits)
return digits
digits.insert(0,carry)#在digits[0]加入carry
print(digits)
return digits
if __name__ == '__main__':
S= Solution()
digits = [1,2,1,9]
S.plusOne(digits
本文介绍了一个简单的算法问题:如何在一个表示非负整数的数字数组上实现加一操作。通过遍历数组并处理进位,文章详细展示了用Python实现该算法的过程。
659

被折叠的 条评论
为什么被折叠?



