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;
}
};
本文介绍了一种解决两个二进制字符串相加的问题的方法。通过反转字符串并逐位进行加法运算,同时处理进位情况,最终得到正确的二进制结果。
1256

被折叠的 条评论
为什么被折叠?



