LeetCode 66 Plus One (Python详解及实现)
2017-08-03 19:23
931 查看
【题目】
Given a non-negative integer represented asa non-empty array of digits, plus one to the integer.
You may assume the integer do not containany leading zero, except the number 0 itself.
The digits are stored such that the mostsignificant digit is at the head of the list.
给定一个数组,将数加一,返回新的数组。比如[9,9],返回[1,0,0]。
【思路】
数组末尾位加1,然后如果进位就向前一个数字加1.
【Python实现】
classSolution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
digits_length = len(digits)
if digits_length == 0:
return [1]
carry = 0#进位
digits[digits_length - 1] += 1#末尾加1
while digits_length > 0:
digits[digits_length - 1] += carry
if digits[digits_length - 1] >= 10:
digits[digits_length - 1], carry= digits[digits_length - 1] % 10, digits[digits_length - 1] // 10
else:
carry = 0
break
digits_length -= 1
if carry == 0:
print(digits)
return digits
digits.insert(0,carry)#在digits[0]加入carry
print(digits)
return digits
if __name__ == '__main__':
S= Solution()
digits = [1,2,1,9]
S.plusOne(digits
Given a non-negative integer represented asa non-empty array of digits, plus one to the integer.
You may assume the integer do not containany leading zero, except the number 0 itself.
The digits are stored such that the mostsignificant digit is at the head of the list.
给定一个数组,将数加一,返回新的数组。比如[9,9],返回[1,0,0]。
【思路】
数组末尾位加1,然后如果进位就向前一个数字加1.
【Python实现】
classSolution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
digits_length = len(digits)
if digits_length == 0:
return [1]
carry = 0#进位
digits[digits_length - 1] += 1#末尾加1
while digits_length > 0:
digits[digits_length - 1] += carry
if digits[digits_length - 1] >= 10:
digits[digits_length - 1], carry= digits[digits_length - 1] % 10, digits[digits_length - 1] // 10
else:
carry = 0
break
digits_length -= 1
if carry == 0:
print(digits)
return digits
digits.insert(0,carry)#在digits[0]加入carry
print(digits)
return digits
if __name__ == '__main__':
S= Solution()
digits = [1,2,1,9]
S.plusOne(digits
相关文章推荐
- LeetCode 64 Minimum Path Sum(Python详解及代码实现)
- [Leetcode]@python 66. Plus One
- LeetCode 74 Search a 2D Matrix(Python详解及实现)
- LeetCode 72 Edit Distance(Python详解及实现)
- LeetCode 78 Subsets (Python详解及实现)
- LeetCode 65 ValidNumer(Python详解及实现)
- LeetCode 56 Merge Intervals(Python实现及详解)
- LeetCode 66 — Plus One(C++ Java Python)
- LeetCode 86 Partition List (Python详解及实现)
- LeetCode 76 Minimum Window Substring(Python详解及实现)
- LeetCode 87 Scramble String (Python详解及实现)
- leetcode 【 Plus One 】python 实现
- 25_LeetCode 82&83. Remove Duplicates from Sorted List(II) (Python详解及实现)
- LeetCode 79 Word Search (Python详解及实现)
- LeetCode 71 Simplify Path(Python详解及实现)
- LeetCode 84 Largest Rectangle in Histogram (Python详解及实现)
- LeetCode 60 Permutation Sequence (Python实现及详解)
- LeetCode 80 Remove Duplicates from Sorted Array II (Python详解及实现)
- LeetCode 61. Rotate List(Python详解及实现)
- LeetCode 73 Set Matrix Zeroes(Python详解及实现)