67. 二进制求和
一杯茶,一包烟,easy代码调半天
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
string addBinary(string a, string b) {
// 用长的当a
if (a.size() < b.size()) {
string tmp = a;
a = b;
b = tmp;
}
int lena = a.size();
int lenb = b.size();
string res = "";
int carry = 0;
char cur = '0';
int i;
//把重叠部分加完
for (i = 1; i <= lenb; i++) {
cur = (carry + a[lena - i] - '0' + b[lenb - i] - '0');
carry = (cur > 1) ? 1 : 0;
cur = cur % 2 + '0';
res = cur + res;
}
//把剩下部分的加完
for (; i <= lena; i++) {
cur = (carry + a[lena - i] - '0');
carry = (cur > 1) ? 1 : 0;
cur = cur % 2 + '0';
res = cur + res;
}
if (carry)
res = '1' + res;
return res;
}
};
int main() {
string a = "100";
string b = "110010";
Solution s;
string res = s.addBinary(a, b);
cout << res;
return 0;
}