Add Binary
题意是计算两个二进制的字符串的和,返回值依然是个二进制字符串。直接写自然不好搞,于是把整个步骤拆解为两个二进制字符与进位相加。实际上任意类似的加法都可以这样拆解。
// add a and b and carry, return a + b + carry.
// carry will be updated when add char.
char add_char(char a, char b, char &c)
{
if (a == b && a == '1')
{
char ret = c;
c = '1';
return ret;
}
else if (a == b && a == '0')
{
char ret = c;
c = '0';
return ret;
}
else
{
if (c == '1')
{
return '0';
}
else
{
return '1';
}
}
}
// Given two binary strings, return their sum (also a binary string).
// For example,
// a = "11"
// b = "1"
// Return "100".
string add_binary(string a, string b)
{
// Init result with the longest string.
string result = a.size() > b.size() ? a : b;
// Init carry with '0'.
char carry = '0';
const char *pa = a.data() + a.size() - 1;
const char *pb = b.data() + b.size() - 1;
string::iterator pc = result.begin() + result.size() - 1;
while (pa != a.data() - 1 || pb != b.data() - 1)
{
if (pa == a.data() - 1)
{
*pc-- = add_char('0', *pb--, carry);
}
else if (pb == b.data() - 1)
{
*pc-- = add_char(*pa--, '0', carry);
}
else
{
*pc-- = add_char(*pa--, *pb--, carry);
}
}
if (carry == '1')
{
return "1" + result;
}
return result;
}