class Solution {
public:
string addBinary(string a, string b) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
string res;
a.size() > b.size() ? res = a: res = b;
int i = a.size() - 1;
int j = b.size() - 1;
int k = res.size() -1;
bool carry = 0;
char x, y;
while (k >= 0)
{
if (i < 0)
x = '0';
else
x = a[i];
if (j < 0)
y = '0';
else
y = b[j];
int temp = x - '0' + y - '0' + carry;
carry = temp >> 1;
temp %= 2;
res[k] = '0' + temp;
--i; --j; --k;
}
if (carry)
res = '1' + res;
return res;
}
};
[Leetcode] Add Binary
最新推荐文章于 2022-05-28 18:30:07 发布