Careercup - Facebook面试题 - 4892713614835712
2014-05-02 09:59
513 查看
2014-05-02 09:54
题目链接
原题:
题目:做二进制加法。
解法:字符串就行了,不需要额外开辟数组。string对象本身就是一个vector,也就是一个数组喽。
代码:
题目链接
原题:
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; }
相关文章推荐
- Careercup - Facebook面试题 - 5765850736885760
- Careercup - Facebook面试题 - 5998719358992384
- Careercup - Facebook面试题 - 4713484755402752
- Careercup - Facebook面试题 - 5344154741637120
- Careercup - Facebook面试题 - 5179916190482432
- Careercup - Facebook面试题 - 5729456584916992
- Careercup - Facebook面试题 - 6026101998485504
- Careercup - Facebook面试题 - 5671785349513216
- Careercup - Facebook面试题 - 4909367207919616
- Careercup - Facebook面试题 - 6685828805820416
- Careercup - Facebook面试题 - 5412018236424192
- Careercup - Facebook面试题 - 23594662
- Careercup - Facebook面试题 - 6139456847347712
- Careercup - Facebook面试题 - 23869663
- Careercup - Facebook面试题 - 4922014007558144
- Careercup - Facebook面试题 - 5761467236220928
- Careercup - Facebook面试题 - 5890898499993600
- Careercup - Facebook面试题 - 5188884744896512
- Careercup - Facebook面试题 - 5435439490007040
- Careercup - Facebook面试题 - 4907555595747328