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

leetcode - Add Binary

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

标签:style   blog   http   color   os   io   ar   for   art   

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

标签:style   blog   http   color   os   io   ar   for   art   

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

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