|
4 | 4 | class Solution { |
5 | 5 | public: |
6 | 6 | string addBinary(string a, string b) { |
7 | | - string result; |
8 | | - int result_length = max(a.length(), b.length()) ; |
| 7 | + string res; |
| 8 | + size_t res_len = max(a.length(), b.length()) ; |
9 | 9 |
|
10 | | - int carry = 0; |
11 | | - for (int i = 0; i < result_length; ++i) { |
12 | | - int a_bit_i = i < a.length() ? a[a.length() - 1 - i] - '0' : 0; |
13 | | - int b_bit_i = i < b.length() ? b[b.length() - 1 - i] - '0' : 0; |
14 | | - int sum = carry + a_bit_i + b_bit_i; |
| 10 | + size_t carry = 0; |
| 11 | + for (int i = 0; i < res_len; ++i) { |
| 12 | + const size_t a_bit_i = i < a.length() ? a[a.length() - 1 - i] - '0' : 0; |
| 13 | + const size_t b_bit_i = i < b.length() ? b[b.length() - 1 - i] - '0' : 0; |
| 14 | + size_t sum = carry + a_bit_i + b_bit_i; |
15 | 15 | carry = sum / 2; |
16 | 16 | sum %= 2; |
17 | | - result.push_back('0' + sum); |
| 17 | + res.push_back('0' + sum); |
18 | 18 | } |
19 | 19 | if (carry) { |
20 | | - result.push_back('0' + carry); |
| 20 | + res.push_back('0' + carry); |
21 | 21 | } |
22 | | - reverse(result.begin(), result.end()); |
| 22 | + reverse(res.begin(), res.end()); |
23 | 23 |
|
24 | | - return result; |
| 24 | + return res; |
| 25 | + } |
| 26 | +}; |
| 27 | + |
| 28 | +class Solution2 { |
| 29 | +public: |
| 30 | + string addBinary(string a, string b) { |
| 31 | + size_t carry = 0; |
| 32 | + string res; |
| 33 | + |
| 34 | + for (auto a_it = a.rbegin(), b_it = b.rbegin(); a_it != a.rend() || b_it != b.rend();) { |
| 35 | + const size_t a_bit_i = (a_it != a.rend()) ? *a_it - '0' : 0; |
| 36 | + const size_t b_bit_i = (b_it != b.rend()) ? *b_it - '0' : 0; |
| 37 | + size_t sum = a_bit_i + b_bit_i + carry; |
| 38 | + carry = sum / 2; |
| 39 | + sum %= 2; |
| 40 | + res.push_back('0' + sum); |
| 41 | + |
| 42 | + if (a_it != a.rend()) { |
| 43 | + ++a_it; |
| 44 | + } |
| 45 | + if (b_it != b.rend()) { |
| 46 | + ++b_it; |
| 47 | + } |
| 48 | + } |
| 49 | + if (carry) { |
| 50 | + res.push_back('0' + carry); |
| 51 | + } |
| 52 | + reverse(res.begin(), res.end()); |
| 53 | + |
| 54 | + return res; |
25 | 55 | } |
26 | 56 | }; |
0 commit comments