題目: LeetCode - 67. Add Binary

題目說明

給兩個 String 代表兩個二進制表示法的數字,求兩數字的和的二進制表示法。

解題思路

從兩數字的最後一位開始往前走,分別將數值加到 c 中,最後存到目前結果的前面。直到兩數都走完且 c 為 0 才停止。

參考解法

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