Skip to content

Commit b6b9f95

Browse files
committed
https://leetcode.cn/problems/design-bitset/
1 parent dcca06d commit b6b9f95

File tree

3 files changed

+60
-0
lines changed

3 files changed

+60
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ leetcode 测试
1010

1111
##### 包含的内容如下
1212

13+
https://leetcode.cn/problems/design-bitset/
14+
1315
https://leetcode.cn/problems/operations-lcci/
1416

1517
https://leetcode.cn/problems/iterator-for-combination/

design-bitset/index.ts

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class Bitset {
2+
#zeros: Set<number>;
3+
#ones = new Set<number>();
4+
constructor(public size: number) {
5+
this.#zeros = new Set<number>(new Array(size).keys());
6+
}
7+
8+
fix(idx: number): void {
9+
this.#ones.add(idx);
10+
this.#zeros.delete(idx);
11+
}
12+
13+
unfix(idx: number): void {
14+
this.#zeros.add(idx);
15+
this.#ones.delete(idx);
16+
}
17+
18+
flip(): void {
19+
[this.#ones, this.#zeros] = [this.#zeros, this.#ones];
20+
}
21+
22+
all(): boolean {
23+
return this.#ones.size === this.size;
24+
}
25+
26+
one(): boolean {
27+
return this.#ones.size > 0;
28+
}
29+
30+
count(): number {
31+
return this.#ones.size;
32+
}
33+
34+
toString(): string {
35+
const bits = new Array(this.size)
36+
.fill(0)
37+
.map((_, i) => (this.#ones.has(i) ? "1" : "0"));
38+
39+
return bits.join("");
40+
}
41+
}
42+
export default Bitset;

design-bitset/test.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import Bitset from "./index.ts";
2+
import { assertEquals } from "https://deno.land/[email protected]/testing/asserts.ts";
3+
4+
Deno.test("design-bitset", () => {
5+
const bs = new Bitset(5); // bitset = "00000".
6+
bs.fix(3); // 将 idx = 3 处的值更新为 1 ,此时 bitset = "00010" 。
7+
bs.fix(1); // 将 idx = 1 处的值更新为 1 ,此时 bitset = "01010" 。
8+
bs.flip(); // 翻转每一位上的值,此时 bitset = "10101" 。
9+
assertEquals(false, bs.all()); // 返回 False ,bitset 中的值不全为 1 。
10+
bs.unfix(0); // 将 idx = 0 处的值更新为 0 ,此时 bitset = "00101" 。
11+
bs.flip(); // 翻转每一位上的值,此时 bitset = "11010" 。
12+
assertEquals(true, bs.one()); // 返回 True ,至少存在一位的值为 1 。
13+
bs.unfix(0); // 将 idx = 0 处的值更新为 0 ,此时 bitset = "01010" 。
14+
assertEquals(2, bs.count()); // 返回 2 ,当前有 2 位的值为 1 。
15+
assertEquals("01010", bs.toString()); // 返回 "01010" ,即 bitset 的当前组成情况。
16+
});

0 commit comments

Comments
 (0)