Add Two Binary Strings
Given two binary numbers as strings, return their sum as a binary string.
We'll cover the following...
Statement
Given two binary numbers as strings, implement a function that performs the binary addition on the strings and returns the output in the form of a string.
Example
Sample input
str1 = "1010100"
str2 = "0100011"
Expected output
"1110111"
Try it yourself
#include <iostream>#include <vector>#include <string>using namespace std;string AddBinary(string str1, string str2) {// TODO: WRITE - CODE - HEREreturn "-1";}
Solution
To solve this problem, we do digit-by-digit addition because we cannot convert the strings to integers. The algorithm for binary addition is given below:
-
First, we initialize an empty
resvariable. -
Then, we initialize the
carryas0. -
Next, we set two pointers,
p1andp2, that point to the end ofstring1andstring2, respectively. -
We traverse the strings from the end using
p1andp2and stop when both strings are done. -
We set
x1equal to a digit from stringstring1at indexp1. Ifp1has reached the beginning ofstring1, we setx1to0. -
We do the same for
x2, settingx2equal to the digit from stringstring2at indexp2. Ifp2reaches the beginning ofstring2, we setx2to0. -
Now, we compute the current value using
value = (x1 + x2 + carry) % 2. Then, we update the carry, like so:carry = (x1 + x2 + carry) / 2. ...