LeetCode 67. Add Binary
Solution1:我的答案
时间复杂度为
O(max{m,n})
O
(
m
a
x
{
m
,
n
}
)
,空间复杂度亦是如此
class Solution {
public:
string addBinary(string a, string b) {
int m = a.size() - 1, n = b.size() - 1;
string res = "";
int sum = 0, carry = 0;
char temp1, temp2;
while (m >=0 || n >= 0) {
if (m < 0) temp1 = '0';
else temp1 = a[m];
if (n < 0) temp2 = '0';
else temp2 = b[n];
sum = (temp1 - '0') + (temp2 - '0') + carry;
carry = sum / 2;
res = char(sum % 2 + '0') + res;
m--;n--;
}
if (carry == 1)
res = char(1 + '0') + res;
return res;
}
};