菱纱梦

导航

Add Binary <leetcode>

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

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

 

算法:模拟加法过程

 1 class Solution {
 2 public:
 3     string addBinary(string a, string b) {
 4         int  len1=a.size();
 5         int  len2=b.size();
 6         int c=0;
 7         reverse(a.begin(),a.end());
 8         reverse(b.begin(),b.end());
 9         string s="";
10         int len=max(len1,len2);
11         for(int i=0;i<len;i++)
12         {
13             int t=0;
14             if(i<len1)  t+=a[i]-'0';
15             if(i<len2)  t+=b[i]-'0';
16             t+=c;
17             c=t/2;
18             s=(char)(t%2+'0')+s;
19         }
20         if(c>0) s=(char)(c+'0')+s;
21         return s;
22     }
23 };

 

posted on 2014-09-30 10:42  菱纱梦  阅读(171)  评论(0编辑  收藏  举报