LeetCode Question: 67. Add Binary (Level : Easy)
Problem Statement: Given two binary strings a and b, return their sum as a binary string.
Note:- Scroll horizontally to see the full line of code.
class Solution
{
public:
string addBinary(string a, string b)
{
int n = a.length() - 1;
int m = b.length() - 1;
string ans;
int c = 0;
while (m > -1 && n > -1)
{
int a1 = int(a[n]) - 48, b1 = int(b[m]) - 48;
int sum = a1 ^ b1 ^ c;
c = (a1 & b1) | (a1 & c) | (b1 & c);
ans.append(to_string(sum));
n--;
m--;
}
while (n > -1)
{
int a1 = int(a[n]) - 48;
int sum = a1 ^ c;
c = a1 & c;
ans.append(to_string(sum));
n--;
}
while (m > -1)
{
int b1 = int(b[m]) - 48;
int sum = b1 ^ c;
c = b1 & c;
ans.append(to_string(sum));
m--;
}
if (c)
{
ans.append(to_string(c));
}
reverse(ans.begin(), ans.end());
return ans;
}
};
Comments
Post a Comment