题目:
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1
or 0
.
Example 1:
Input: a = "11", b = "1" Output: "100"
Example 2:
Input: a = "1010", b = "1011" Output: "10101"
代码:
class Solution {
public:
string addBinary(string a, string b) {
string res;
int alen = a.size();
int blen = b.size();
int temp = 0;
for (int i = alen - 1, j = blen - 1; i >= 0 || j >= 0; i--, j--) {
int ai = 0, bi = 0, t = 0;
if (i >= 0 && j >= 0) {
ai = a[i] -'0';
bi = b[j] - '0';
t = ai + bi + temp;
}
else if (i >= 0) {
ai = a[i] - '0';
t = ai + temp;
}
else {
bi = b[j] - '0';
t = bi + temp;
}
res += to_string(t % 2);
temp = t / 2;
}
if (temp > 0) {
res += to_string(temp);
}
int len = res.size();
for (int i = 0; i < len / 2; i++) {
int j = len - 1 - i;
char temp = res[i];
res[i] = res[j];
res[j] = temp;
}
return res;
}
};