leetcode-67- add binary

题目

二进制数字相加,返回二进制字符串

分析

举例说明:
输入”11”,”1”,返回”100”

C++代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution{
public:
string (string a, string b) {
string res = "";
int len_a = a.length();
int len_b = b.length();
int carry = 0;
while(len_a > 0 || len_b > 0){

int abit = len_a > 0 ? a[len_a-1] - '0' : 0;
int bbit = len_b > 0 ? b[len_b-1] - '0' : 0;
int cbit = carry > 0 ? 1 : 0;
//字符串存在insert函数,可以直接调用
res.insert(res.begin(), '0' + ((abit + bbit + cbit) & 1));
carry = (abit + bbit + cbit) / 2;
len_a--;
len_b--;
}
if(carry > 0)
res.insert(res.begin(), '0' + carry);
return res;
}
};