Careercup - Facebook面试题 - 4892713614835712

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,也就是一个数组喽。

代码:

 1 // http://www.careercup.com/question?id=4892713614835712

 2 #include <iostream>

 3 #include <string>

 4 using namespace std;

 5 

 6 string binaryAdd(string &a, string &b)

 7 {

 8     if (a.length() > b.length()) {

 9         return binaryAdd(b, a);

10     }

11     

12     string c;

13     int carry;

14     int na, nb;

15     int bita, bitb;

16     int i;

17 

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

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

20     

21     na = (int)a.length();

22     nb = (int)b.length();

23     carry = 0;

24     for (i = 0; i < nb; ++i) {

25         bita = i < na ? a[i] - '0' : 0;

26         bitb = b[i] - '0';

27         c.push_back((bita ^ bitb ^ carry) + '0');

28         carry = (bita + bitb + carry) > 1;

29     }

30     if (carry) {

31         c.push_back('1');

32     }

33     reverse(c.begin(), c.end());

34 

35     return c;

36 }

37 

38 int main()

39 {

40     string a, b, c;

41     

42     while (cin >> a >> b) {

43         c = binaryAdd(a, b);

44         cout << c << endl;

45     }

46     

47     return 0;

48 }

 

你可能感兴趣的:(Facebook)