Skip to content

Instantly share code, notes, and snippets.

@zhoutuo
Created March 31, 2013 07:10
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 zhoutuo/5279845 to your computer and use it in GitHub Desktop.
Save zhoutuo/5279845 to your computer and use it in GitHub Desktop.
Given two binary strings, return their sum (also a binary string). For example, a = "11" b = "1" Return "100".
class Solution {
public:
string addBinary(string a, string b) {
string c;
int lenA = a.length() - 1;
int lenB = b.length() - 1;
int left = 0;
while(lenA >= 0 or lenB >= 0 or left != 0) {
int tmpA = lenA >= 0 ? a[lenA] - '0' : 0;
int tmpB = lenB >= 0 ? b[lenB] - '0' : 0;
int sum = tmpA + tmpB + left;
left = 0;
if(sum >= 2) {
++left;
sum -= 2;
}
c.push_back(sum + '0');
--lenA;
--lenB;
}
for(int i = 0; i < c.length() / 2; ++i) {
swap(c[i], c[c.length() - i - 1]);
}
return c;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment