VOOZH about

URL: https://www.geeksforgeeks.org/dsa/adding-one-to-number-represented-as-array-of-digits/

⇱ Adding one to number represented as array of digits - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Adding one to number represented as array of digits

Last Updated : 31 Oct, 2025

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 = 125

Input : [9, 9, 9]
Output: 1000
Explanation: 999 + 1 = 1000

[Approach - 1] - Using Carry - O(n) Time and O(1) Space

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.

Output
1000

Time Complexity: O(n), where n is the size of array.
Space Complexity: O(1)

[Approach - 2] - O(n) Time and O(1) Space

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.

Output
1000

Time Complexity: O(n), where n is the number of digits / size of the array.
Auxiliary Space: O(1)

[Alternate Approach] - O(n) Time and O(1) Space

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.


Output
1000

Time Complexity: O(n), where n is the number of digits / size of the array.
Auxiliary Space: O(1)


Comment
Article Tags: