Skip to content

Commit

Permalink
Update add-binary.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
kamyu104 committed Feb 19, 2016
1 parent f2ad6af commit 9c38ca4
Showing 1 changed file with 41 additions and 11 deletions.
52 changes: 41 additions & 11 deletions C++/add-binary.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,53 @@
class Solution {
public:
string addBinary(string a, string b) {
string result;
int result_length = max(a.length(), b.length()) ;
string res;
size_t res_len = max(a.length(), b.length()) ;

int carry = 0;
for (int i = 0; i < result_length; ++i) {
int a_bit_i = i < a.length() ? a[a.length() - 1 - i] - '0' : 0;
int b_bit_i = i < b.length() ? b[b.length() - 1 - i] - '0' : 0;
int sum = carry + a_bit_i + b_bit_i;
size_t carry = 0;
for (int i = 0; i < res_len; ++i) {
const size_t a_bit_i = i < a.length() ? a[a.length() - 1 - i] - '0' : 0;
const size_t b_bit_i = i < b.length() ? b[b.length() - 1 - i] - '0' : 0;
size_t sum = carry + a_bit_i + b_bit_i;
carry = sum / 2;
sum %= 2;
result.push_back('0' + sum);
res.push_back('0' + sum);
}
if (carry) {
result.push_back('0' + carry);
res.push_back('0' + carry);
}
reverse(result.begin(), result.end());
reverse(res.begin(), res.end());

return result;
return res;
}
};

class Solution2 {
public:
string addBinary(string a, string b) {
size_t carry = 0;
string res;

for (auto a_it = a.rbegin(), b_it = b.rbegin(); a_it != a.rend() || b_it != b.rend();) {
const size_t a_bit_i = (a_it != a.rend()) ? *a_it - '0' : 0;
const size_t b_bit_i = (b_it != b.rend()) ? *b_it - '0' : 0;
size_t sum = a_bit_i + b_bit_i + carry;
carry = sum / 2;
sum %= 2;
res.push_back('0' + sum);

if (a_it != a.rend()) {
++a_it;
}
if (b_it != b.rend()) {
++b_it;
}
}
if (carry) {
res.push_back('0' + carry);
}
reverse(res.begin(), res.end());

return res;
}
};

0 comments on commit 9c38ca4

Please sign in to comment.