Skip to content

Instantly share code, notes, and snippets.

@adamkorg
Last active September 30, 2019 18:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamkorg/7f7cc67a39fe8198ccdf1974c4eb7961 to your computer and use it in GitHub Desktop.
Save adamkorg/7f7cc67a39fe8198ccdf1974c4eb7961 to your computer and use it in GitHub Desktop.
Leetcode 67: Add Binary
#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