首页 > 其他 > 详细

leetcode - Add Binary

时间:2014-09-09 15:26:58      阅读:125      评论:0      收藏:0      [点我收藏+]

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

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

字符串相加,不难

 

个人思路:

1,尾部对齐,然后逐位相加,flag记为进位

代码:

bubuko.com,布布扣
 1 #include <string>
 2 
 3 using namespace std;
 4 
 5 class Solution {
 6 public:
 7     string addBinary(string a, string b) {
 8         if (a.empty())
 9         {
10             return b;
11         }
12         if (b.empty())
13         {
14             return a;
15         }
16 
17         int aLen = a.length();
18         int bLen = b.length();
19         int i = aLen - 1, j = bLen - 1;
20         int flag = 0; //进位
21         int temp, ai, bj;
22         string result;
23 
24         for (; i >= 0 || j >= 0; --i, --j)
25         {
26             ai = i >= 0 ? (a[i] - 0) : 0;
27             bj = j >= 0 ? (b[j] - 0) : 0;
28 
29             temp = ai + bj + flag;
30             flag = temp > 1 ? 1 : 0;
31             temp = temp - flag * 2;
32 
33             result.insert(result.begin(), temp + 0);
34         }
35 
36         if (flag)
37         {
38             result.insert(result.begin(), 1);
39         }
40 
41         return result;
42     }
43 };
View Code

 

leetcode - Add Binary

原文:http://www.cnblogs.com/laihaiteng/p/3962382.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!