Solution: Add Binary
Let's solve the Add Binary problem.
We'll cover the following
The idea is to add binary numbers bit by bit while keeping track of any carry that occurs during the process. We iterate through both input strings in reverse order, calculate the sum and carry for each bit, update the result, and finally handle any remaining carry. The result is a valid binary sum of the two input binary strings.
Here are the steps of the algorithm:
-
Initialize two variables:
result: This list will store the binary sum in reverse order.carry: This variable will keep track of any carry that occurs during the addition process and is initialized with .
-
Initialize two pointers to traverse the binary strings in reverse order:
-
ptr1: This pointer will traversestr1. -
ptr2: This pointer will traversestr2.
-
-
Traverse the strings in reverse order using the above pointers:
-
Extract the binary digits at the current position of
ptr1andptr2. If either pointer goes beyond the string’s length, is used for that string. -
Calculate the sum,
total_sum, of the current digits along withcarryfrom the previous step. -
The
current_digitis computed as remainder oftotal_sumwhen divided by , representing the current bit value. -
carryfor the next iteration is updated by dividingtotal_sumby . -
current_digitis appended toresult. -
Both
ptr1andptr2are moved one position to the left.
-
-
Repeat step until the strings are completely traversed.
-
If there is still a carry left i.e,
carry = 1, it’s appended toresult. -
resultcontains binary sum in reverse order. It is reversed, converted to string, and returned.
Let’s look at the following illustration to get a better understanding of the solution:
1 of 10
2 of 10
3 of 10
4 of 10
5 of 10
6 of 10
7 of 10
8 of 10
9 of 10
10 of 10
Let’s implement the algorithm as discussed above:
Time complexity#
The time complexity of this solution is str1 and str2 respectively. This is because the loop will run until the longest string has been traversed.
Space complexity#
The space complexity of this solution is result to store the binary sum.
Add Binary
String to Integer (atoi)