LeetCode 67 Add Binary

好久不写博客了,最近有跳槽的打算,所以打算重新刷一遍LeetCode,顺便在这里做一点笔记

https://leetcode.com/problems/add-binary/

#67 的Add Binary,大意就是使用string的方式实现两个二进制字符串的加法,思路很简单,先寻找到较长的那个字符串,之后开始从两个字符串的尾部遍历做加法,之所以需要考虑较长字符串,是因为存在1111 + 10这样的情况

使用vector存放最后的输出结果

 1 #define max(a,b) (((a) > (b)) ? (a) : (b))
 2 #define min(a,b) (((a) < (b)) ? (a) : (b))
 3 
 4 class Solution {
 5 public:
 6     string addBinary(string a, string b) {
 7         int max_len = max(a.length(), b.length());
 8         int min_len = min(a.length(), b.length());
 9         int carry = 0, temp = 0;
10         int index;
11         vector<char> ret;
12         string *long_binary;
13         string *shot_binary;
14         if (max_len == a.length()){
15             long_binary = &a;
16             shot_binary = &b;
17         }
18         else{
19             long_binary = &b;
20             shot_binary = &a;
21         }
22         for (int index = 1; index <= max_len; index++){
23             if (index > min_len){
24                 temp = carry + ((*long_binary)[max_len - index] - '0');
25             }
26             else{
27                 temp = carry + ((*long_binary)[max_len - index] - '0') + ((*shot_binary)[min_len - index] - '0');
28             }
29             carry = 0;
30             if (temp == 2){
31                 temp = 0;
32                 carry = 1;
33             }
34             else if (temp == 3){
35                 temp = 1;
36                 carry = 1;
37             }
38             ret.insert(ret.begin(), '0' + temp);
39         }
40         if (carry == 1)
41             ret.insert(ret.begin(), '1');
42         string result;
43         result.insert(result.begin(), ret.begin(), ret.end());
44         return result;
45     }
46 };

 

posted @ 2016-07-26 01:45  Berne  阅读(156)  评论(0编辑  收藏  举报