67. Add Binary
- Total Accepted: 92800
- Total Submissions: 327327
- Difficulty: Easy
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
Subscribe to see which companies asked this question
Show Similar Problems
Have you met this question in a real interview?
Yes
No
class Solution {
public:
string addBinary(string a, string b) {
reverse(a.begin(),a.end());
reverse(b.begin(),b.end());
string ans="";
int big=0;
int len=max(a.length(),b.length());
int x;
int y;
for(int i=0;i<len;i++)
{
if(i>=a.length()) x=0;
else x=a[i]-'0';
if(i>=b.length()) y=0;
else y=b[i]-'0';
ans=ans+(char)((x+y+big)%2+'0');
big=x+y+big>1 ? 1:0;
}
if(big) ans=ans+"1";
reverse(ans.begin(),ans.end());
return ans;
}
};