leetcode-67-Add-Binary

描述


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

For example,
a = “11”
b = “1”
Return “100”.

分析


如果是其他进制的加法,改代码中的两行即可

解决方案1(C++)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
string addBinary(string a, string b) {
int carry = 0;
string result;

for(int i = a.size()-1, j = b.size()-1; i >= 0 || j >= 0; i--,j--) {
int oper1 = i>=0?a[i]-'0':0;
int oper2 = j>=0?b[j]-'0':0;
int val = (oper1 + oper2 + carry) % 2;
carry = (oper1 + oper2 + carry) / 2;

result.insert(result.begin(), val+'0');
}
if(carry == 1) {
result.insert(result.begin(), '1');
}
return result;
}
};

相关问题


题目来源