4.Add Binary
Given two binary strings, return their sum (also a binary string).
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
Solution:
class Solution
{
public:
string addBinary(string a, string b)
{
int l1 = a.length() - 1;
int l2 = b.length() - 1;
string s = "";
int res, carry = 48;
int x,y,sum;
while (l1 >= 0 && l2 >= 0)
{
x = int(a[l1]);
y = int(b[l2]);
res = (x + y + carry) % 2;
carry = (x + y + carry - 48)/2;
cout<<carry<<" ";
if (res == 0)
{
s = '0' + s;
}
else
{
s = '1' + s;
}
l1--;
l2--;
}
while (l1 >= 0)
{
x = int(a[l1]);
res = (x + carry) % 2;
carry = (x + carry) / 2;
if (res == 0)
{
s = '0' + s;
}
else
{
s = '1' + s;
}
l1--;
}
while (l2 >= 0)
{
x = int(b[l2]);
res = (x + carry) % 2;
carry = (x + carry) / 2;
if (res == 0)
{
s = '0' + s;
}
else
{
s = '1' + s;
}
l2--;
}
if (carry != 48)
{
s='1'+s;
}
return s;
}
};
Time Complexity : O(n+m)
Last updated