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

Add Binary

时间:2015-06-17 13:07:29      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:

Description:

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

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

Code:

 1     string addBinary(string a, string b) {
 2     //4ms
 3     const char * shortStr = (a.size()<=b.size())?a.c_str():b.c_str();
 4     const char * longStr = (a.size()>b.size())?a.c_str():b.c_str();
 5     int lenShort = strlen(shortStr);
 6     int lenLong = strlen(longStr);
 7     
 8     string s="";
 9     int temp;
10     int flag = 0;
11     for (int i = 0; i < lenShort; ++i)
12     {
13         temp = shortStr[lenShort-1-i]-0+longStr[lenLong-1-i]-0+ flag;
14         flag = temp/2;
15         s.insert(0,1,0+temp%2);
16     }
17    
18     for (int i = lenLong-1-lenShort; i >=0; --i)
19     {
20         temp = longStr[i]-0+flag;
21         flag = temp/2;
22         s.insert(0,1,0+temp%2);
23     }
24     
25     if (flag == 1)
26         s.insert(0,1,1);
27     return s;
28     }

 

Add Binary

标签:

原文地址:http://www.cnblogs.com/happygirl-zjj/p/4582853.html

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