[LeetCode] Design Bitset

2166. Design Bitset

A Bitset is a data structure that compactly stores bits.

Implement the Bitset class:

  • Bitset(int size) Initializes the Bitset with size bits, all of which are 0.
  • void fix(int idx) Updates the value of the bit at the index idx to 1. If the value was already 1, no change occurs.
  • void unfix(int idx) Updates the value of the bit at the index idx to 0. If the value was already 0, no change occurs.
  • void flip() Flips the values of each bit in the Bitset. In other words, all bits with value 0 will now have value 1 and vice versa.
  • boolean all() Checks if the value of each bit in the Bitset is 1. Returns true if it satisfies the condition, false otherwise.
  • boolean one() Checks if there is at least one bit in the Bitset with value 1. Returns true if it satisfies the condition, false otherwise.
  • int count() Returns the total number of bits in the Bitset which have value 1.
  • String toString() Returns the current composition of the Bitset. Note that in the resultant string, the character at the ith index should coincide with the value at the ith bit of the Bitset.
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class Bitset {
bool bits[100000];
int size;
int oneCount;
bool fliped;
public:
Bitset(int size): size(size), oneCount(0), fliped(false) {
memset(bits, false, sizeof(bool)*size);
}

void fix(int idx) {
oneCount += (fliped == bits[idx] ? 1 : 0);
bits[idx] = !fliped;
}

void unfix(int idx) {
oneCount += (fliped ^ bits[idx] ? -1 : 0);
bits[idx] = fliped;
}

void flip() {
fliped = !fliped;
oneCount = size - oneCount;
}

bool all() {
return oneCount == size;
}

bool one() {
return oneCount;
}

int count() {
return oneCount;
}

string toString() {
stringstream ss;
for(int i = 0; i < size; i++) {
ss<<(bits[i] == fliped ? '0' : '1');
}
return ss.str();
}
};

/**
* Your Bitset object will be instantiated and called as such:
* Bitset* obj = new Bitset(size);
* obj->fix(idx);
* obj->unfix(idx);
* obj->flip();
* bool param_4 = obj->all();
* bool param_5 = obj->one();
* int param_6 = obj->count();
* string param_7 = obj->toString();
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/08/PS/LeetCode/design-bitset/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.