66. Plus One
Array, Math ·Problem Statement
link: https://leetcode.com/problems/plus-one/ https://leetcode.cn/problems/plus-one/
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.
Example:
Input: digits = [1,2,3]
Output: [1,2,4]
Input: digits = [4,3,2,1]
Output: [4,3,2,2]
Input: digits = [9]
Output: [1,0]
Solution Approach
Simulate the process of elementary addition starting from the least significant digit.
Algorithm
- Iteration: Begin from the last digit, adding one.
- Carry Management: If it becomes 10, set it to 0 and carry one to the previous digit.
- Overflow: If all digits are 9, prepend a 1 to handle overflow.
Implement
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
for i in range(len(digits)-1, -1, -1):
if digits[i] == 9:
digits[i] = 0
else:
digits[i] += 1
return digitas
return [1] + digits