您的位置:首页 > 职场人生

Careercup - Facebook面试题 - 4892713614835712

2014-05-02 09:59 513 查看
2014-05-02 09:54

题目链接

原题:

You have two numbers decomposed in binary representation, write a function that sums them and returns the result.

Input: 100011, 100100
Output: 1000111


题目:做二进制加法。

解法:字符串就行了,不需要额外开辟数组。string对象本身就是一个vector,也就是一个数组喽。

代码:

// http://www.careercup.com/question?id=4892713614835712 #include <iostream>
#include <string>
using namespace std;

string binaryAdd(string &a, string &b)
{
if (a.length() > b.length()) {
return binaryAdd(b, a);
}

string c;
int carry;
int na, nb;
int bita, bitb;
int i;

reverse(a.begin(), a.end());
reverse(b.begin(), b.end());

na = (int)a.length();
nb = (int)b.length();
carry = 0;
for (i = 0; i < nb; ++i) {
bita = i < na ? a[i] - '0' : 0;
bitb = b[i] - '0';
c.push_back((bita ^ bitb ^ carry) + '0');
carry = (bita + bitb + carry) > 1;
}
if (carry) {
c.push_back('1');
}
reverse(c.begin(), c.end());

return c;
}

int main()
{
string a, b, c;

while (cin >> a >> b) {
c = binaryAdd(a, b);
cout << c << endl;
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: