Python 官方文档:入门教程 => 点击学习
给定一个非空的数值数组代表一个非负整数,对整数进行加一操作 整数最高位存放在数组头位,数组中每一个元素都代表一个数字 你可以认为整数不以0开头,除了数字0以外 Example 1: Input: [1,2,3] Output: [1,
给定一个非空的数值数组代表一个非负整数,对整数进行加一操作
整数最高位存放在数组头位,数组中每一个元素都代表一个数字
你可以认为整数不以0开头,除了数字0以外
Example 1:
Input: [1,2,3] Output: [1,2,4] Explanation: The array represents the integer 123.
Example 2:
Input: [4,3,2,1] Output: [4,3,2,2] Explanation: The array represents the integer 4321.
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
extra = 0 #进位
one = 1 #加一
digits = digits[::-1]
for index, num in enumerate(digits):
if num+one+extra == 10: #判断是否进位
extra = 1
one = 0
digits[index] = 0
else: #不进位就直接输出
digits[index] = num+one+extra
return digits[::-1]
digits.append(1)
return digits[::-1]
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
sum = 0
for index, num in enumerate(digits):
sum += num*(10**(len(digits)-index-1))
sum += 1
new_list = []
for i in str(sum):
new_list.append(int(i))
return new_list
算法题来自:https://LeetCode-cn.com/problems/plus-one/description/
--结束END--
本文标题: Python实现"加一"的两种方法
本文链接: https://www.lsjlt.com/news/184424.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0