You are given a large integer represented as an array digits
, where each digits[i]
is the i-th
digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The integer does not contain any leading zeroes.
Your task is to increment the integer by one and return the resulting array of digits.
Before we proceed, let’s clarify a few things:
digits
will not contain any leading zeroes except for the number zero itself?
999
to 1000
), we need to insert a 1
at the beginning of the list.def plusOne(digits):
# Start from the end of the array
for i in reversed(range(len(digits))):
# If the current digit is less than 9, simply increment it by 1 and return the modified list
if digits[i] < 9:
digits[i] += 1
return digits
# Otherwise, set the current digit to 0
digits[i] = 0
# If we exit the loop, it means we had a carry out from the most significant digit
# This means all digits were 9 initially, so we need an extra digit at the beginning
return [1] + digits
# Example usage:
print(plusOne([1, 2, 3])) # Output: [1, 2, 4]
print(plusOne([4, 3, 2, 1])) # Output: [4, 3, 2, 2]
print(plusOne([9])) # Output: [1, 0]
print(plusOne([9, 9, 9])) # Output: [1, 0, 0, 0]
This solution handles the carry propagation effectively and works for the general case when dealing with very large numbers represented as arrays of digits.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?