LC066 - Plus One
Problem
You are given a large integer represented as an integer array digits
, where each digits[i]
is the ith
digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0
's.
Increment the large integer by one and return the resulting array of digits.
Solution
Naive
def plusOne(self, digits: List[int]) -> List[int]:
if digits[-1] < 9:
digits[-1] += 1
else:
carry = True
# iterate each digit from the last digit
for i in range(len(digits)-1, -1, -1):
# add carry
if carry:
digits[i] += 1
if digits[i] >= 10:
carry = True
digits[i] -= 10
else:
carry = False
break
# add to start of list if carry remains
if carry:
digits.insert(0, 1)
return digits
Last updated