![]() |
VOOZH | about |
Given a non-negative number represented as an array of digits. The task is to add 1 to the number (increment the number represented by the digits by 1). The digits are stored such that the most significant digit is the first element of the array.
Examples :
Input : [1, 2, 4]
Output : 125
Explanation: 124 + 1 = 125Input : [9, 9, 9]
Output: 1000
Explanation: 999 + 1 = 1000
Table of Content
To add one to the number represented by digits, follow the below steps :
- Parse the given array from the end as we do in school addition.
- If the last elements are 9, make it 0 and carry = 1.
- For the next iteration check carry and if it adds to 10, do the same as step 2.
- After adding carry, make carry = 0 for the next iteration.
- If the carry still remains after traversing the entire array, append 1 in the beginning.
1000
Time Complexity: O(n), where n is the size of array.
Space Complexity: O(1)
The idea is to start from the end of the vector and if the element is 9 set it to 0, else increment the digit by 1 and exit the loop.
- If the loop set all digits to 0 (if all digits were 9) insert 1 at the beginning.
- Else increment the element at the position where the loop stopped.
1000
Time Complexity: O(n), where n is the number of digits / size of the array.
Auxiliary Space: O(1)
To avoid inserting at front of array, we can firstly reverse the array, and then append the value at the last. Thereafter, we can reverse the array again to get the result.
1000
Time Complexity: O(n), where n is the number of digits / size of the array.
Auxiliary Space: O(1)