You are given two non-negative integers, ‘NUM1’ and ‘NUM2’, in the form of strings. Return the sum of both strings.
You do not need to print anything, it has already been taken care of. Just implement the given function.
Example:
Let ‘NUM1’ be: “5”
Let ‘NUM2’ be: “21”
The sum of both numbers will be: “26”.
The first line of the input contains an integer, 'T’, denoting the number of test cases.
The first line of each test case contains two strings, ‘NUM1’ and ‘NUM2’, representing the two non-negative integers.
Output Format :
For each test case, print the sum of both the strings.
Print the output of each test case in a separate line.
1 <= T <= 10
1 <= |NUM1|, |NUM2| <= 10^5
NUM1 and NUM2 don’t have leading zeroes.
Where |NUM1| and |NUM2| denote the length of the respective strings.
Time limit: 1 sec
2
5 21
10 9
26
19
For the first test case:
The sum of both numbers will be: “26”.
For the second test case:
The sum of both numbers will be: “19”.
2
9 9
21 10
18
31
Try to add the characters of the strings individually.
The basic idea is to add the character of the strings individually. We run a loop on both strings simultaneously from the end of the strings and add the sum of the characters. We also keep track of carry and update the result. If at any point sum of characters becomes greater than 9, we update the carry to 1.
Here is the algorithm:
O(|NUM1| + |NUM2|), where |NUM1| and |NUM2| are the length of the strings.
We traverse both the strings once, which takes time equal to their lengths. Therefore, the overall time complexity will be O(|NUM1| + |NUM2|).
O(1)
We don’t use any extra space. Therefore, the overall space complexity will be O(1).