#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
string addBinary(string a, string b) {
int sa = a.size(), sb = b.size();
int stridx = sb>sa?sb:sa;
char *str = new char[stridx + 1];
str[stridx] = '\0';
cout << stridx << endl;
stridx--;
bool fwbit = false;
while (sa > 0 && sb > 0)
{
if (a[sa - 1] == '1' && b[sb - 1] == '1')
{
if (fwbit)
str[stridx] = '1';
else
str[stridx] = '0';
fwbit = true;
}
else if (a[sa - 1] == '1' || b[sb - 1] == '1')
{
if (fwbit)
{
str[stridx] = '0';
fwbit = true;
}
else
{
str[stridx] = '1';
fwbit=false;
}
}
else
{
if (fwbit)
str[stridx] = '1';
else
str[stridx] = '0';
fwbit = false;
}
sa--;
sb--;
stridx--;
}
while (sb > 0)
{
if (fwbit)
{
if (b[sb - 1] == '1')
{
str[stridx] = '0';
}
else
{
str[stridx] = '1';
fwbit = false;
}
}
else
str[stridx] = b[sb - 1];
sb--;
stridx--;
}
while (sa > 0)
{
if (fwbit)
{
if (a[sa - 1] == '1')
str[stridx] = '0';
else
{
str[stridx] = '1';
fwbit = false;
}
}
else
str[stridx] = a[sa - 1];
sa--;
stridx--;
}
string sum(str);
if (fwbit)
{
sum.insert(0, 1, '1');
}
delete str;
return sum;
}
int main(int argc, char *argv[])
{
string a("100");
string b("110011110");
string c = addBinary(a,b);
cout << c << endl;
return 0;
}
【leetcode】67.Add Binary
最新推荐文章于 2022-04-09 11:43:16 发布