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

leetcode 【 Plus One 】python 实现

2015-01-16 22:39 459 查看
题目

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.

代码:oj测试通过 Runtime: 47 ms

class Solution:
# @param digits, a list of integer digits
# @return a list of integer digits
def plusOne(self, digits):
if digits is None:
return None
if len(digits) == 0 :
return digits
length = len(digits)
new_last_digit = digits[length-1] + 1
if new_last_digit / 10 == 0:
digits[length-1] = new_last_digit
return digits
else:
jinwei = 1
digits[length-1] = 0
for i in range(length-2,-1,-1):
curr_value = jinwei + digits[i]
if curr_value/10 == 0:
digits[i] = curr_value
return digits
else:
digits[i] = curr_value % 10
digits.insert(0,1)
return digits


思路

先排除special case

然后就逐渐往前加,维护一个jinwei变量

注意 如果最后有进位 需要在数组开头再补充一个1 这里用到了insert函数 之前还不知道python数组有这个函数
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: