LeetCode 题解之Add Binary

1、题目描述

2、题目分析

使用string 的逆向指针,做二进制加法,注意进位问题就可以。

3、代码

 1 string addBinary(string a, string b) {
 2        
 3         string::reverse_iterator it_a = a.rbegin() ;
 4         string::reverse_iterator it_b = b.rbegin() ;
 5         
 6         string s;
 7         string s0 = "0";
 8         string s1 = "1";
 9         int up = 0;
10         while( it_a != a.rend() && it_b != b.rend() ){
11             if( *it_a - '0'  + *it_b - '0'  + up == 1 ){
12                 s = s1 + s;
13                 up = 0;
14             }else if( *it_a - '0' + *it_b - '0' + up == 0 ){
15                 s = s0 + s;
16                 up = 0;
17             }else if( *it_a - '0' + *it_b - '0' + up == 2 ){
18                 s = s0 + s;
19                 up=1;
20             }else if( *it_a - '0' + *it_b - '0' + up == 3 ){
21                 s = s1 + s;
22                 up = 1;
23             }
24             ++it_a ;
25             ++it_b ;
26         }
27         
28         while( it_a != a.rend() ){
29             if( *it_a - '0' + up ==  0 ){
30                 s = s0 + s;
31                 up = 0;
32             }else if( *it_a - '0' + up == 1){
33                 s = s1 + s;
34                 up = 0;
35             }else{
36                 s = s0 + s;
37                 up = 1;
38             }
39             ++it_a ;
40         }
41         
42         while( it_b != b.rend() ){
43             if( *it_b - '0' + up == 0 ){
44                 s = s0 + s;
45                 up = 0;
46             }else if(*it_b - '0' + up == 1){
47                 s = s1 + s;
48                 up =0;
49             }else{
50                 s = s0 + s;
51                 up = 1;
52             }
53             ++it_b;
54         }
55         
56         if( up == 1 ){
57             s = s1 + s;
58         }
59         
60         return s;
61         
62     }

 

posted @ 2018-07-12 09:05  山里的小勇子  阅读(149)  评论(0编辑  收藏  举报