Skip to content

Instantly share code, notes, and snippets.

@pdu
Created February 2, 2013 15:05
Show Gist options
  • Select an option

  • Save pdu/4697732 to your computer and use it in GitHub Desktop.

Select an option

Save pdu/4697732 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". http://leetcode.com/onlinejudge#question_67
class Solution {
public:
string addBinary(string a, string b) {
string ret;
int lena = a.length();
int lenb = b.length();
int t = 0;
int i = lena - 1;
int j = lenb - 1;
while (i >= 0 || j >= 0) {
int s = t;
if (i >= 0)
s += a[i--] - '0';
if (j >= 0)
s += b[j--] - '0';
if (s == 0 || s == 2)
ret.append("0");
else
ret.append("1");
if (s >= 2)
t = 1;
else
t = 0;
}
if (t == 1)
ret.append("1");
reverse(ret.begin(), ret.end());
return ret;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment