#2166

Design Bitset

expert · 1095 · lc medium +32 · 32.6% accepted · 612 likes · top 10%

Description

A Bitset is a data structure that stores bits compactly.

Implement the Bitset class:

- Bitset(int size) Initializes the Bitset with size bits, all set to 0.

- void fix(int idx) Sets the bit at index idx to 1. If already 1, no change.

- void unfix(int idx) Sets the bit at index idx to 0. If already 0, no change.

- void flip() Inverts every bit: all 0s become 1s and vice versa.

- boolean all() Returns true if every bit is 1, otherwise false.

- boolean one() Returns true if at least one bit is 1, otherwise false.

- int count() Returns the total number of bits currently set to 1.

- String toString() Returns the current bit sequence as a string where the character at position i reflects the ith bit's value.

Example 1:

Input
["Bitset", "fix", "fix", "flip", "all", "unfix", "flip", "one", "unfix", "count", "toString"]
[[5], [3], [1], [], [], [0], [], [], [0], [], []]
Output
[null, null, null, null, false, null, null, true, null, 2, "01010"]

Example 2:

Explanation
Bitset bs = new Bitset(5); // bitset = "00000".
bs.fix(3); // the value at idx = 3 is updated to 1, so bitset = "00010".
bs.fix(1); // the value at idx = 1 is updated to 1, so bitset = "01010".
bs.flip(); // the value of each bit is flipped, so bitset = "10101".
bs.all(); // return False, as not all values of the bitset are 1.
bs.unfix(0); // the value at idx = 0 is updated to 0, so bitset = "00101".
bs.flip(); // the value of each bit is flipped, so bitset = "11010".
bs.one(); // return True, as there is at least 1 index with value 1.
bs.unfix(0); // the value at idx = 0 is updated to 0, so bitset = "01010".
bs.count(); // return 2, as there are 2 bits with value 1.
bs.toString(); // return "01010", which is the composition of bitset.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36