标签:
Given two binary strings, return their sum (also a binary string).
For example,
a = “11”
b = “1”
Return “100”.
两个字符串,计算加法。这道题主要是考察对字符串操作的掌握情况。另外,加法要从低位算起,但是输出时要先输出高位。因此,需要将计算结果先存下来,然后再逆序输出。
访问字符串的字符可以采用传统的 c 语言那种数组下标的方式。也可以用 iterator。
下标方式的代码如下:
string addBinary(string a, string b)
{
int n1 = a.length() - 1;
int n2 = b.length() - 1;
char ai, bi, ci, carry = 0;
stack<char> out;
while (n1 >= 0 || n2 >= 0)
{
ai = (n1 >= 0) ? a[n1--] - ‘0‘ : 0;
bi = (n2 >= 0) ? b[n2--] - ‘0‘ : 0;
ci = ai + bi + carry;
carry = (ci > 1) ? 1 : 0;
ci = ci & 0x01;
out.push(ci);
}
if(carry > 0) out.push(carry);
string c;
while(!out.empty())
{
ci = out.top() + ‘0‘;
c.push_back(ci);
out.pop();
}
return c;
}
iterator 方式有点特殊,对字符串逆序遍历需要用 reverse_iterator。代码如下:
string addBinary(string a, string b)
{
string::const_reverse_iterator ita = a.crbegin();
string::const_reverse_iterator itb = b.crbegin();
char ai, bi, ci, carry = 0;
stack<char> out;
while (ita != a.crend() || itb != b.crend())
{
ai = (ita != a.crend()) ? *ita++ - ‘0‘ : 0;
bi = (itb != b.crend()) ? *itb++ - ‘0‘ : 0;
ci = ai + bi + carry;
carry = (ci > 1) ? 1 : 0;
ci = ci & 0x01;
out.push(ci);
}
if(carry > 0) out.push(carry);
string c;
while(!out.empty())
{
ci = out.top() + ‘0‘;
c.push_back(ci);
out.pop();
}
return c;
}
标签:
原文地址:http://blog.csdn.net/liyuanbhu/article/details/51814868