首页 > 编程语言 > 详细

leetcode 【 Plus One 】python 实现

时间:2015-01-16 23:35:50      阅读:363      评论:0      收藏:0      [点我收藏+]

题目

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

 1 class Solution:
 2     # @param digits, a list of integer digits
 3     # @return a list of integer digits
 4     def plusOne(self, digits):
 5         if digits is None:
 6             return None
 7         if len(digits) == 0 :
 8             return digits
 9         length = len(digits)
10         new_last_digit = digits[length-1] + 1
11         if new_last_digit / 10 == 0:
12             digits[length-1] = new_last_digit
13             return digits
14         else:
15             jinwei = 1
16             digits[length-1] = 0
17             for i in range(length-2,-1,-1):
18                 curr_value = jinwei + digits[i]
19                 if curr_value/10 == 0:
20                     digits[i] = curr_value
21                     return digits
22                 else:
23                     digits[i] = curr_value % 10
24             digits.insert(0,1)
25             return digits

思路

先排除special case

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

注意 如果最后有进位 需要在数组开头再补充一个1 这里用到了insert函数 之前还不知道python数组有这个函数

leetcode 【 Plus One 】python 实现

原文:http://www.cnblogs.com/xbf9xbf/p/4229893.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!