Created
July 19, 2020 08:09
-
-
Save JyotinderSingh/d55da3d65dc46d3124c506e42ffc8d2a to your computer and use it in GitHub Desktop.
Add Binary (LeetCode) | Interview Question Explanation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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