diff --git a/87. Add Binary/README.md b/87. Add Binary/README.md new file mode 100644 index 0000000..c094847 --- /dev/null +++ b/87. Add Binary/README.md @@ -0,0 +1,20 @@ +这道题从思路上算是简单题,但处理的时候细心一点,没太大问题。 + +两个字符串,肯定从尾部开始迭代起,时刻计算三个东西:a 的当前位(abit),b 的当前位(bbit),进位(carry)。 + +那么计算后 ret 的当前位即为: +```cpp +// 奇数为1,偶数为0 +ret = (abit + bbit + carry) & 0x1 : "1" : "0" + ret; +// 或者可以直接使用 XOR +ret = abit ^ bbit ^ carry : "1" : "0" + ret; +``` + +计算后进位即为: +```cpp +carry = abit + bbit + carry >= 2; // 只需判断是否大于2即可 +``` + +最后,迭代的时候要注意,短的字符串迭代完,继续判断长的字符串,若长短都判断完,还有进位要判断。故循环条件显然应该是:`apos || bpos || carry`,不存在的当前位,用 `0x0` 来替代运算即可。 + +为了节省字节数,我使用的 bool 来进行全程操作,你也可以采用 short or int. diff --git a/87. Add Binary/TEST.cc b/87. Add Binary/TEST.cc new file mode 100644 index 0000000..4cbd180 --- /dev/null +++ b/87. Add Binary/TEST.cc @@ -0,0 +1,12 @@ +#define CATCH_CONFIG_MAIN +#include "../Catch/single_include/catch.hpp" +#include "solution.h" + +using std::vector; + +TEST_CASE("Add Binary", "[addBinary]") +{ + Solution s; + REQUIRE( s.addBinary("11", "1") == "100" ); + REQUIRE( s.addBinary("111", "10") == "1001" ); +} diff --git a/87. Add Binary/solution.h b/87. Add Binary/solution.h new file mode 100644 index 0000000..cc8f19b --- /dev/null +++ b/87. Add Binary/solution.h @@ -0,0 +1,18 @@ +#include +using std::string; + +class Solution { +public: + string addBinary(string a, string b) { + string ret; + bool carry{false}; + for (auto apos=a.size(), bpos=b.size(); apos || bpos || carry; ) { + bool abit{apos && a[--apos] == '1'}; + bool bbit{bpos && b[--bpos] == '1'}; + ret = (abit ^ bbit ^ carry ? "1" : "0") + ret; + carry = abit + bbit + carry >= 2; + } + return ret; + } +}; +