https://leetcode.com/problems/plus-one/#/description
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.
翻譯
- 給定一個(gè)代表非負(fù)整數(shù)的列表,其中每一個(gè)值代表該位的數(shù)值。
- 對(duì)該整數(shù)+1,返回新的列表
- 比如 19=[1,9] 19+1=20=[2, 0]
分析
- 設(shè)置進(jìn)位符 carry=0
- 逆序遍歷列表
- 所有元素均+carry list[i] += carry
- 若list[i]+carry = 10,則list[i] = 0, carry = 1; 否則carry = 0
- 若遍歷結(jié)束時(shí),carry == 1,則需要新加入一個(gè)[1],放入列表最前面,即
- [9] ->[1, 0]
# Time O(n)
class Solution(object):
def plusOne(self, digits):
carry = 0
for i in range(len(digits)-1, -1, -1):
digits[i] += carry
if i == len(digits) - 1:
digits[i] += 1
if digits[i] == 10:
digits[i] = 0
carry = 1 # 進(jìn)位標(biāo)志
else:
carry = 0
if carry == 1:
digits.insert(0, 1)
return digits