67 Add Binary
Given two binary strings, return their sum (also a binary string).
For example,
a = "11", b = "1"
Return "100".
Solution:
class Solution {
public:
string addBinary(string a, string b) {
int na = a.size(), nb = b.size();
int ia, ib, ic = 0;
string res;
for ( int i = 0; i <= max(na, nb)-1; i++ ) {
if ( na-1-i <= -1 ) ia = 0;
else {
string sa = a.substr(na-1-i, 1);
ia = atoi(sa.c_str());
}
if ( nb-1-i <= -1 ) ib = 0;
else {
string sb = b.substr(nb-1-i, 1);
ib = atoi(sb.c_str());
}
cout << ia << ib << ic << endl;
int sum = ia + ib + ic;
if ( sum == 3 ) { res += '1'; ic = 1;}
if ( sum == 2 ) { res += '0'; ic = 1;}
if ( sum == 1 ) { res += '1'; ic = 0;}
if ( sum == 0 ) { res += '0'; ic = 0;}
}
if ( ic == 1 ) res += '1';
int i = 0, j = res.size()-1;
while ( i <= j ) swap(res[i++], res[j--]);
return res;
}
};
Notes: cast a character (or string) to integer.
// num = int(s[i])
string subStr = s.substr(i, 1);
int num = atoi(subStr.c_str());