您的位置:首页 > 编程语言 > Python开发

[LeetCode]Plus One@python

2018-01-27 16:29 393 查看
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.

解法一:

将list按位乘10转化为int数,+1后再转换为字符串,最后转换为数组返回

class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
num = 0
for i in range(len(digits)):
num = num*10 + digits[i]
return [int(i) for i in str(num+1)]

解法二:

直接加1,立一个flag

class Solution:
# @param digits, a list of integer digits
# @return a list of integer digits
def plusOne(self, digits):
flag = 1
for i in range(len(digits)-1, -1, -1):
if digits[i] + flag == 10:
digits[i] = 0
flag = 1
else:
digits[i] = digits[i] + flag
flag = 0

if flag == 1:
digits.insert(0, 1)
return digits
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode