Created
December 28, 2012 20:50
-
-
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
This file contains hidden or 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 <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