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

leetcode 67. Add Binary

时间:2015-03-07 18:36:26      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:

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

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

[Solution]

 1 string addBinary(string a, string b) 
 2     {
 3         if (a.size() == 0)
 4             return b;
 5         if (b.size() == 0)
 6             return a;
 7         
 8         reverse(a.begin(), a.end());
 9         reverse(b.begin(), b.end());
10         int carry = 0, i = 0;
11         string c = "";
12         while (i < a.size() || i < b.size())
13         {
14             int x = (i < a.size()) ? (a[i] - 0) : 0;
15             int y = (i < b.size()) ? (b[i] - 0) : 0;
16             if ((x + y + carry) & 1)
17                 c += "1";
18             else
19                 c += "0";
20             carry = (x + y + carry) >> 1;
21             i++;
22         }
23         if (carry > 0)
24             c += "1";
25         reverse(c.begin(), c.end());
26         
27         return c;
28     }

 

leetcode 67. Add Binary

标签:

原文地址:http://www.cnblogs.com/ym65536/p/4320659.html

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