Last active
September 30, 2019 18:56
-
-
Save adamkorg/7f7cc67a39fe8198ccdf1974c4eb7961 to your computer and use it in GitHub Desktop.
Leetcode 67: Add Binary
This file contains 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
#include <iostream> | |
#include <string> | |
using namespace std; | |
string addBinary(string a, string b) { | |
string result(max(a.size(), b.size()), '0'); | |
int carry=0, k=result.size()-1; | |
for (int i=a.size()-1, j=b.size()-1; i>=0 || j>=0; --i,--j) { | |
int sum = 0; | |
if (i>=0) sum += (a[i]-'0'); | |
if (j>=0) sum += (b[j]-'0'); | |
sum += carry; | |
carry = 0; | |
if (sum>1) { | |
carry = 1; | |
sum -= 2; | |
} | |
result[k--] = ('0'+sum); | |
} | |
if (carry > 0) | |
result.insert(result.begin(), '1'); | |
return result; | |
} | |
int main() { | |
cout << addBinary("1010", "1011") << "\n"; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment