LeetCode 67. Add Binary

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

这个题目只要注意各种情况你就成功了一大半,特别要注意的是对进位赋值后可能产生的变化,以及最后一位进位为1时,

我们要把这个1插进来。同时注意字符串的低位是我们数值的高位

class Solution {
public:
string addBinary(string a, string b) {
reverse(begin(a), end(a));
reverse(begin(b), end(b));
string result;
char num = '';
int i = ;
for (;i < a.size() && i < b.size();++i)
{
if (a[i] == ''&&b[i] == ''&&num == '')
{
result.insert(begin(result), '');
}
if (a[i] == ''&&b[i] == ''&&num == '')
{
result.insert(begin(result), '');
}
if ((a[i] == ''&&b[i] == ''&&num == '') || (a[i] == ''&&b[i] == ''&&num == '') ||
(a[i] == ''&&b[i] == ''&&num == ''))
{
result.insert(begin(result), '');
num = '';
}
if (a[i] == ''&&b[i] == ''&&num == '' || a[i] == ''&&b[i] == ''&&num == '' ||
a[i] == ''&&b[i] == ''&&num == '')
{
result.insert(begin(result), '');
num = '';
}
}
if (i == a.size())
{
for (;i < b.size();++i)
{
if (b[i] == ''&&num == '')
result.insert(begin(result), '');
if (b[i] == ''&&num == '' || b[i] == ''&&num == '')
{
result.insert(begin(result), '');
num = '';
}
if (b[i] == ''&&num == '')
result.insert(begin(result), '');
}
}
else
{
for (;i < a.size();++i)
{
if (a[i] == ''&&num == '')
result.insert(begin(result), '');
if (a[i] == ''&&num == '')
result.insert(begin(result), '');
if (a[i] == ''&&num == '' || a[i] == ''&&num == '')
{
result.insert(begin(result), '');
num = '';
} }
}
if (num == '')result.insert(begin(result), '');
return result;
}
};
上一篇:【LeetCode】67. Add Binary 解题报告(Python)


下一篇:进程间通信(1)—windows消息