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
思路:
先排除special case
然后就逐渐往前加,维护一个jinwei变量
注意 如果最后有进位 需要在数组开头再补充一个1 这里用到了insert函数 之前还不知道python数组有这个函数
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数组有这个函数
相关文章推荐
- LeetCode 66 Plus One (Python详解及实现)
- [LeetCode]2 Median of Two Sorted Arrays (C++,Python实现)
- [LeetCode]4 Add Two Numbers(C++,Python实现)
- leetcode 【 Linked List Cycle II 】 python 实现
- leetcode 【 Reorder List 】python 实现
- leetcode 【 Reverse Nodes in k-Group 】 python 实现
- LeetCode 66 — Plus One(C++ Java Python)
- leetcode 【 Copy List with Random Pointer 】 python 实现
- leetcode 【 Intersection of Two Linked Lists 】python 实现
- leetcode 【Rotate List 】python 实现
- leetcode 【 Partition List 】python 实现
- [LeetCode]5 Longest Palindromic Substring(C++,Python实现)
- [leetcode]Plus One @ Python
- 【LeetCode with Python】 Plus One
- leetcode 【 Reverse Words in a String 】python 实现
- [LeetCode]3 Longest Substring Without Repeating Characters (C++,Python实现)
- leetcode add to numbers python实现
- leetcode 【 Remove Nth Node From End of List 】 python 实现
- leetcode 【 Sort List 】 python 实现
- leetcode 【 Merge k Sorted Lists 】python 实现