Created
March 31, 2013 07:10
-
-
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".
This file contains 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
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