码迷,mamicode.com
首页 > 其他好文 > 详细

Add Binary <leetcode>

时间:2014-09-30 11:05:31      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   for   sp   div   c   

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 };

 

Add Binary <leetcode>

标签:style   blog   color   io   ar   for   sp   div   c   

原文地址:http://www.cnblogs.com/sqxw/p/4001511.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!