LeetCode 66 Plus One (Python详解及实现)
【题目】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. Th
【题目】
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
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
所有评论(0)