Skip to content

Commit

Permalink
added 87. Add Binary
Browse files Browse the repository at this point in the history
  • Loading branch information
pezy committed Jan 9, 2015
1 parent fd87cf2 commit 1927541
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 0 deletions.
20 changes: 20 additions & 0 deletions 87. Add Binary/README.md
Original file line number Diff line number Diff line change
@@ -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.
12 changes: 12 additions & 0 deletions 87. Add Binary/TEST.cc
Original file line number Diff line number Diff line change
@@ -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" );
}
18 changes: 18 additions & 0 deletions 87. Add Binary/solution.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
#include <string>
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;
}
};

0 comments on commit 1927541

Please sign in to comment.