Sum of Big integers.

Posted: 5 Mar, 2021
Difficulty: Easy

PROBLEM STATEMENT

Try Problem

You have been given two integers ‘NUM1’ and ‘NUM2’ as a string. Your task is to print the sum of both the numbers.

Input Format:
The first line contains a single integer ‘T’ representing the number of test cases. The 'T' test cases are as follows: 

The only line of each test case contains two space-separated integers ‘NUM1’ and ‘NUM2’ representing two integers whose sum you need to return. As numbers are pretty large ‘NUM1’ and ‘NUM2’ will be provided as strings.
Note:
You do not need to print anything; it has already been taken care of. Just implement the function.
Output Format:
For each test case, print the sum of two numbers.
Constraints:
1 <= T <= 10000
1 <= NUM1 <= 10^50
1 <= NUM2 <= 10^50

Where ‘T’ is the number of test cases. ‘NUM1’ and ‘NUM2’ are the numbers whose sum you have to compute.  

Time Limit: 1sec
Approach 1

 

 

Let us store ‘NUM1’ and ‘NUM2’ as strings rather than storing them as integers. We will calculate the sum as follows: 

 

  1. We will add zeroes before the smaller string among ‘NUM1’ and ‘NUM2’ and make them of equal length.
  2. We will add one more zero before both the numbers because the sum of both the numbers can contain at most one extra digit than the larger number.
  3. We will start adding from the unit’s place i.e backward.
  4. We will also define a variable ‘CARRY’ which stores carry from the previous position. Initially, it will be initialized to zero.
  5. At the ith position, we can calculate the value by (‘NUM1[i]’ - ‘0’+ ‘NUM2[i]’- ‘0’ + ‘CARRY’) modulus ‘10’.
  6. ‘CARRY’ for the next position i.e. ‘i’-1th position will be (‘NUM1[i]’ - ‘0’+ ‘NUM2[i]’- ‘0’ + ‘CARRY’)/10.
  7. Remove leading zeroes from the answer.
  8. Return the ‘SUM’.
Try Problem