Last Updated: 21 Nov, 2020
Easy
Problem statement

#### Binary strings are the representation of integers in the binary form. For example, the binary strings of 9 and 16 are β1001β and β10000β respectively.

##### Input Format:
``````The first line contains a single integer βTβ representing the number of test cases.

The second line contains two space-separated integers βNβ and βMβ which are the length of strings βAβ and βBβ respectively.

The third line of each test case will contain two space-separated binary strings βAβ and βBβ as described above.
``````
##### Output Format:
``````For each test case, print the sum of the given binary strings in a binary form.

Output for every test case will be printed in a separate line.
``````
##### Note:
``````You donβt need to print anything; It has already been taken care of. Just implement the given function.
``````
##### Constraints:
``````1 <= T <= 5
1 <= N, M <= 5000

βAβ and βBβ consist only of '0' or '1' characters.

Each string does not contain leading zeros except for the zero itself.

Time limit: 1 sec
``````
Approaches

## 01Approach

The basic idea of this approach is to start doing bit by bit addition while keeping track of the carry bit from the least significant bits, i.e. from the end of the strings. Let say βaβ is the current bit of βAβ and βbβ is the current bit of βBβ and βcβ is the carry bit. Now, we want to add those bits and get the resulting βsumβ and new βcarryβ bits. Consider the boolean table:

After observing closely, we can find the βSUMβ is (βaβ + βbβ + βcβ) % 2 and βCARRYβ is (βaβ + βbβ + βcβ) / 2.

Steps are as follows:

1. Initialise a βCARRYβ variable with zero which will store the carry and create an empty string βSUMβ to store the sum of both binary strings.
2. Start iterating from the end of the strings.
• Let say we are currently considering the ith element from the end.
• Initialise a βCUR_SUMβ variable with zero to store the current sum.
• If the ith element exists for the string βAβ i.e. βiβ <= βNβ
• Add the value of that element in βCUR_SUMβ i.e. βCUR_SUMβ = βCUR_SUMβ + A[N - i]
• If the ith element exists for the string βB,β i.e. βiβ <= βMβ
• Add the value of that element in βCUR_SUMβ i.e. βCUR_SUMβ = βCUR_SUMβ + B[M - i]
• Add the previous carry to βCUR_SUMβ.
• Append (βCUR_SUMβ % 2) at the end of the βSUMβ string. And assign (βCUR_SUMβ / 2) to βCARRYβ i.e. βCARRYβ = (βCUR_SUMβ / 2).
3. If βCARRYβ is 1, append β1β at the end of the βSUMβ string.
4. Reverse the βSUMβ string and return it.