Skip to content

Instantly share code, notes, and snippets.

@JyotinderSingh
Created July 19, 2020 08:09
Show Gist options
  • Save JyotinderSingh/d55da3d65dc46d3124c506e42ffc8d2a to your computer and use it in GitHub Desktop.
Save JyotinderSingh/d55da3d65dc46d3124c506e42ffc8d2a to your computer and use it in GitHub Desktop.
Add Binary (LeetCode) | Interview Question Explanation
class Solution {
public:
string addBinary(string a, string b) {
string res;
int i = a.size() - 1, j = b.size() - 1;
int sum, carry = 0;
while(i >= 0 || j >= 0) {
sum = carry;
if(i >= 0) sum += a[i--] - '0';
if(j >= 0) sum += b[j--] - '0';
res += to_string(sum % 2);
carry = sum / 2;
}
if(carry != 0) res += '1';
reverse(res.begin(), res.end());
return res;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment