Add One To Number

Last updated: 29th Aug, 2020

         

Problem Statment

Given a non-negative number represented as an array of digits, add 1 to the number ( increment the number represented by the digits ). The digits are stored such that the most significant digit is at the head of the list.

Example 1:

If the vector has [1, 2, 3]
The returned vector should be [1, 2, 4]

Approach:

Reverse the digits of the number to make your life easier. Maintain a carry which is initialized to 1 ( Denoting that we need to add one to the number ). Run a loop on the digit array ( which is now reversed ), and add carry to the current digit. If the digit D exceeds 10 on doing so, store the last digit in current position ( D % 10 ), and make carry = rest of the digits ( D / 10 ). Continue the process till you have covered all the digits. Now if at the end, carry = 0, we are done, and we can return the array. If not, we need to add one more digit, with carry in it.

Python Code
class Solution:

    def plusOne(self,A):
        val = 1;
        for i in range(len(A),0,-1):
            val = val + A[i-1]
            borrow = int(val/10)
            if borrow == 0:
                A[i-1] = val
                break;
            else:
                A[i-1] = val%10
                val = borrow
        A = [borrow] + A
        while A[0] == 0:
            del A[0]
        return A


C++ Code
class solution
{
public:
    vector plusOne(vector& arr)
    {
       int n = arr.size();

       arr[n-1] += 1;
       int hand = arr[n-1]/10;
       arr[n-1] = arr[n-1] % 10;

        for (int i=n-2; i>=0; i--)
        {
            if (hand == 1)
            {
               arr[i] += 1;
               hand = arr[i]/10;
               arr[i] = arr[i] % 10;
            }
        }

        if (hand == 1)
          arr.insert(arr.begin(), 1);
            return arr;
      }
};