首页 > 代码库 > [LeetCode] [Add Binary 2012-04-02 ]

[LeetCode] [Add Binary 2012-04-02 ]

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

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

string 的操作,短string补位。两个“0”会输出一个“00”,要特殊处理,plus如果最后为“1”,要补上。

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
class Solution {
public:
     
    char getBit(string s, int n)
    {
        if(n >= s.length())
        {
            return ‘0‘;
        }
        else
        {
            return s[n];
        }
    }
     
    char Add(char a, char b, char c, char &remain)
    {
        if(a == ‘1‘ && b==‘1‘ && c==‘1‘)
        {
            remain = ‘1‘;
            return ‘1‘;
        }
        if((a == ‘1‘ && b == ‘1‘) || (a == ‘1‘ && c == ‘1‘) || (c == ‘1‘ && b == ‘1‘))
        {
            remain =‘0‘;
            return ‘1‘;
        }
        if(a == ‘0‘ && b ==‘0‘ && c ==‘0‘)
        {
            remain = ‘0‘;
            return ‘0‘;
        }
        remain = ‘1‘;
        return ‘0‘;
    }
     
    string addBinary(string a, string b) {
        int n1 = a.length();
        int n2 = b.length();
        int n = n1;
        if(n1 > n2)
        {
            n = n1;
            b = string(n1-n2, ‘0‘) + b;
        }
         
        else if(n1 < n2)
        {
            n = n2;
            a = string(n2-n1, ‘0‘) + a;
        }
         
        if(a=="0" && b =="0")   return "0";
         
        string sum = "FIRST";
        char plus = ‘0‘;
        char remain = ‘0‘;
        for(int i = n-1; i>=0 ;i--)
        {
            plus = Add(a[i],b[i],plus, remain);
            if(sum == "FIRST")
            {
                sum = string (1, remain);
            }
            else
            {
                sum = string(1,remain) + sum;
            }
        }
        if(plus == ‘1‘)
        {
            sum = string(1,plus) + sum;
        }
        return sum;
    }
};