From 9c38ca4d0ca97dffcebe3f1dc044e93ffc125398 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 19 Feb 2016 21:32:17 +0800 Subject: [PATCH] Update add-binary.cpp --- C++/add-binary.cpp | 52 ++++++++++++++++++++++++++++++++++++---------- 1 file changed, 41 insertions(+), 11 deletions(-) diff --git a/C++/add-binary.cpp b/C++/add-binary.cpp index eaac45a64..1c3591b60 100644 --- a/C++/add-binary.cpp +++ b/C++/add-binary.cpp @@ -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; } };