Add Binary

2013.12.22 03:31

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

Solution:

  This is a problem about big integer addition, only in that it's binary. My solution is to add them up bit by bit, reverse the char array and return the result as std::string.

  Time compexity is O(max(m, n)), space complexity is O(max(m, n)), where m and n are the length of two strings.

Accepted code:

 1 #define __MAIN__
 2 #ifdef __MAIN__
 3 #include <string>
 4 using namespace std;
 5 #endif
 6 
 7 class Solution {
 8 public:
 9     string addBinary(string a, string b) {
10         // Note: The Solution object is instantiated only once and is reused by each test case.
11         if(a.length() < b.length()){
12             return addBinary(b, a);
13         }
14         
15         if(a == "0"){
16             return b;
17         }else if(b == "0"){
18             return a;
19         }
20         
21         int i;
22         char *buf = nullptr, tmp;
23         int lena, lenb;
24         
25         lena = a.length();
26         lenb = b.length();
27         buf = new char[lena + 2];
28         for(i = 0; i < lena + 2; ++i){
29             buf[i] = 0;
30         }
31         for(i = 0; i < lena; ++i){
32             buf[i] += (a[lena - 1 - i] - '0');
33         }
34         for(i = 0; i < lenb; ++i){
35             buf[i] += (b[lenb - 1 - i] - '0');
36         }
37         for(i = 0; i < lena + 1; ++i){
38             buf[i + 1] += buf[i] / 2;
39             buf[i] %= 2;
40         }
41         for(i = 0; i < lena + 1; ++i){
42             buf[i] += '0';
43         }
44         for(i = 0; i < lena - i; ++i){
45             tmp = buf[i];
46             buf[i] = buf[lena - i];
47             buf[lena - i] = tmp;
48         }
49         
50         string res;
51         if(buf[0] > '0'){
52             res = string(buf);
53         }else{
54             res = string(buf + 1);
55         }
56         delete[] buf;
57         
58         return res;
59     }
60 };

 

 posted on 2013-12-22 03:36  zhuli19901106  阅读(295)  评论(0编辑  收藏  举报