Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
// Only need to pay attention that adding is from the end of string.
This problem is similar to the add one problem. http://blog.csdn.net/github_34333284/article/details/51103310
#include <string>
#include <iostream>
using namespace std;
// a = "11", b = "1" --> "100"
string addBinary(string a, string b) {
if(a.size() == 0) return b;
if(b.size() == 0) return a;
int aSize = a.size() - 1;
int bSize = b.size() - 1;
string res = "";
int overflow = 0;
while(aSize >= 0 && bSize >= 0) {
int tmp = a[aSize] - '0' + b[bSize] - '0' + overflow;
overflow = tmp / 2;
res = to_string(tmp % 2) + res;
aSize--;
bSize--;
}
while(aSize >= 0) {
int tmp = a[aSize--] - '0' + overflow;
overflow = tmp / 2;
res = to_string(tmp % 2) + res;
}
while(bSize >= 0) {
int tmp = b[bSize--] - '0' + overflow;
overflow = tmp / 2;
res = to_string(tmp % 2) + res;
}
if(overflow) res = "1" + res;
return res;
}
int main(void) {
string a = "11";
string b = "1";
string res = addBinary(a, b);
cout << res << endl;
}
Maybe It is better to make code clean.
#include <string>
#include <iostream>
using namespace std;
string addBinary(string a, string b) {
if(a.size() == 0) return b;
if(b.size() == 0) return a;
int aEnd = a.size() - 1;
int bEnd = b.size() - 1;
int overflow = 0;
string res = "";
while(aEnd >= 0 || bEnd >= 0) {
int sum = (aEnd < 0 ? 0 : (a[aEnd] - '0')) + (bEnd < 0 ? 0 : (b[bEnd] - '0')) + overflow;
overflow = sum / 2;
sum = sum % 2;
res = to_string(sum) + res;
aEnd--;
bEnd--;
}
if(overflow) res = "1" + res;
return res;
}
int main(void) {
cout << addBinary("11", "1") << endl;
}