class Solution {
public:
string addBinary(string a, string b) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
string str;
if (a.empty() && b.empty()) {
return str;
}
int i = a.size() - 1;
int j = b.size() - 1;
int carry = 0;
int sum;
while (i > -1 || j > -1 || carry) {
sum = 0;
sum += carry;
if (i > -1) {
sum += a[i] - '0';
i--;
}
if (j > -1) {
sum += b[j] - '0';
j--;
}
carry = sum / 2;
sum = sum % 2;
if (sum == 0) {
str.insert(0, "0");
}
else {
str.insert(0, "1");
}
}
return str;
}
};
LeetCode Add Binary
最新推荐文章于 2022-05-28 18:30:07 发布