66. Plus One
LeetCode 66. Plus One
Description
Given a non-empty array of decimal digits representing a non-negative integer, increment one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example 1:
Constraints:
1 <= digits.length <= 100
0 <= digits[i] <= 9
Tags
Math, Array
Solution
We initialize a variable c
with 1 for the carry. Traverse the array from the right. We add c onto the current digit and reset c = 0
(IMPORTANT). Then we check if the current digit is larger than 9, if it is then update the carry and this digit in Add Two Numbers manner. After loop, we need to check if there is still a carry, if c ≠ 0
, we need to append c
in front of the digits
.
Complexity
Time complexity:
Space complexity:
Code
Last updated
Was this helpful?