LeetCode Add Binary

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

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

 

这题用数组来做可能更简单,但考虑到可能面试的时候要求不能开额外的数组,就只能对string操作了。最主要的是把进位这部分写对。

 1 class Solution {
 2 public:
 3     string addBinary(string a, string b) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         int flag = 0;
 7         
 8         int aIndex = a.size() - 1;
 9         int bIndex = b.size() - 1;
10         
11         string c;
12         
13         while(aIndex >= 0 && bIndex >= 0)
14         {
15             int num = a[aIndex] - '0' + (b[bIndex] - '0') + flag;
16             flag = num / 2;
17             num %= 2;
18             
19             c = (char)(num + '0') + c;
20             
21             aIndex--;
22             bIndex--;
23         }
24         
25         while(aIndex >= 0)
26         {
27             int num = a[aIndex] - '0' + flag;
28             flag = num / 2;
29             num %= 2;
30             
31             c = (char)(num + '0') + c;
32             
33             aIndex--;
34         }
35         
36         while(bIndex >= 0)
37         {
38             int num = b[bIndex] - '0' + flag;
39             flag = num / 2;
40             num %= 2;
41             
42             c = (char)(num + '0') + c;
43             
44             bIndex--;
45         }
46         
47         if (flag > 0)
48             c = (char)(flag + '0') + c;
49             
50         return c;
51     }
52 };
posted @ 2012-10-27 19:23  chkkch  阅读(4174)  评论(0编辑  收藏  举报