题目链接:Add Binary

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

For example,

a = "11"
b = "1"
Return "100".

这道题的要求是两个二进制字符串加法运算。

简单的大数加法,只不过是二进制的。处理进位的时候,按照二进制处理即可。

时间复杂度:O(n)

空间复杂度:O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution
{
public:
    string addBinary(string a, string b)
    {
        string s = "";
        
        int c = 0, i = a.size() - 1, j = b.size() - 1;
        while(i >= 0 || j >= 0 || c == 1)
        {
            c += i >= 0 ? a[i --] - '0' : 0;
            c += j >= 0 ? b[j --] - '0' : 0;
            s = char(c % 2 + '0') + s;
            c /= 2;
        }
        
        return s;
    }
};