Add Binary

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

For example,
a = “11”
b = “1”
Return “100”.

C++:
01 string addBin(string a, string b)
02 {
03     string s;
04     int carry=0;
05     int m=a.size();
06     int n=b.size();
07 
08     for(int i=1;i<=n;i++){
09         int sum=carry+a[mi]+b[ni]‘0’‘0’;
10         if(sum>=2)
11             carry=1;
12         else
13             carry=0;
14         if(sum%2)
15             s.insert(0,“1”);
16         else
17             s.insert(0,“0”);
18     }
19     for(int i=n+1;i<=m;i++){
20         int sum=carry+a[mi]‘0’;
21         if(sum>=2)
22             carry=1;
23         else
24             carry=0;
25         if(sum%2)
26             s.insert(0,“1”);
27         else
28             s.insert(0,“0”);
29     }
30     if(carry)
31         s.insert(0,“1”);
32     return s;
33 }
34 
35 string addBinary(string a, string b)
36 {
37     string s;
38     int carry=0;
39     int m=a.size();
40     int n=b.size();
41     if(m>=n)
42         return addBin(a,b);
43     else
44         return addBin(b,a);
45 }
Advertisements
This entry was posted in String. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s