Add One To Number Represented As An Array

Companies:
  • Google Interview Questions

Given a non-empty array of digits representing a non-negative integer, plus 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 contain a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

Example 1:

Input: [3,4,3,6]

Output: [3,4,3,7]

Example 2:

Input: [6,7,3,9]

Output: [6,7,4,0]

Solution

The problem is simple, but we need to take care of two situations:

  1. If any digit in a given array is 9.
  2. If all the digits in a given array are 9.

If any digit of a number is 9:

  • Change the value of the digit of that index to 0.
  • Increment the next occuring digit by one.

The implementation is done using an iterative approach:

  1. Traverse through the given array representing a number from the end to the start.
  2. If the digit is less than 9, then just increment the current digit and return the array and break the loop.
  3. If above condition is not true then change the value of that digit to 0 (because the digit is equal to 9).
  4. If all the digits in the given array are equal to 9:
  5. If all the digits are equal to 9, then the above will never return any value and this loop will change all the 9’s to 0’s. For example: if the number is 999 then it will become 000.
  6. Create a new array whose length will be equal to length of the original array plus 1.
  7. Initialize element at index 0 to 1 and simple return it.

Solution Implementation

#include <iostream>
#include <vector>
using namespace std;

int main() {
    // your code goes here
    vector<int> number = { 6, 7, 3, 9 };
    int carry = 1;
    for(int i = number.size() - 1 ; i >= 0; i--) {
        number[i] += carry;
        carry = number[i]/10;
        number[i] = number[i]%10;
    }
    
    // Inserts at the begining of the vector
    if (carry != 0) {
        number.insert(number.begin(), carry);
    }
    
    for(int i = 0; i < number.size(); i++) {
        cout << number[i];
    }
    cout << "\n";
    
    return 0;
}

 

Complexity Analysis:

  • Time Complexity: O(n).
  • Space Complexity: O(1), since we are not using any extra space.
Scroll to Top