Careercup - Facebook面试题 - 4892713614835712

时间:2022-10-30 14:45:59

2014-05-02 09:54

题目链接

原题:

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

Input: ,
Output:

题目:做二进制加法。

解法:字符串就行了,不需要额外开辟数组。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 = ;
for (i = ; i < nb; ++i) {
bita = i < na ? a[i] - '' : ;
bitb = b[i] - '';
c.push_back((bita ^ bitb ^ carry) + '');
carry = (bita + bitb + carry) > ;
}
if (carry) {
c.push_back('');
}
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 ;
}