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
res
variable. -
Then, we initialize the
carry
as0
. -
Next, we set two pointers,
p1
andp2
, that point to the end ofstring1
andstring2
, respectively. -
We traverse the strings from the end using
p1
andp2
and stop when both strings are done. -
We set
x1
equal to a digit from stringstring1
at indexp1
. Ifp1
has reached the beginning ofstring1
, we setx1
to0
. -
We do the same for
x2
, settingx2
equal to the digit from stringstring2
at indexp2
. Ifp2
reaches the beginning ofstring2
, we setx2
to0
. -
Now, we compute the current value using
value = (x1 + x2 + carry) % 2
. Then, we update the carry, like so:carry = (x1 + x2 +
...