Skip to content

Instantly share code, notes, and snippets.

@pdu
Created December 28, 2012 20:50
Show Gist options
  • Select an option

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

Select an option

Save pdu/4401733 to your computer and use it in GitHub Desktop.
Given two binary strings, return their sum (also a binary string). http://www.leetcode.com/onlinejudge
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
class Solution {
public:
string addBinary(string a, string b) {
stringstream ss(stringstream::in | stringstream::out);
int addon = 0;
int idx_a = a.length() - 1;
int idx_b = b.length() - 1;
while (idx_a >= 0 || idx_b >= 0) {
if (idx_a >= 0) {
addon += a[idx_a] - '0';
idx_a--;
}
if (idx_b >= 0) {
addon += b[idx_b] - '0';
idx_b--;
}
ss << addon % 2;
addon /= 2;
}
if (addon != 0) {
ss << addon;
}
string ret;
ss >> ret;
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