Implementation of C++ Bitset using String
Let’s implement bitset in C++, such that following operations can be performed in stated time complexities :
- init(int size): initializes a bitset of size number of 0 bits.
- void fix(int pos): Change the bit at position pos to 1. No change if it was already 1.
- void unfix(int pos): Change the bit at position pos to 0. No change if it was already 0.
- void flip(): Change all 1s to 0s and all 0s to 1s.
- bool check() : If all values of bitset are 1 , return true , else return false.
- bool checkOne() : If at least one bit is 1 , return true. Else return false.
- int countOne() : return number of bits whose value is 1.
- string Value(): returns the current value of bitset in form of a string.
The init(size) must have O(size) complexity (approximately). The rest of the operations must have constant complexity.
O(size/d) where d can be 32 or 64(depending upon bits).
Implementation: The required implementation can be done easily by maintaining a string of a given size and performing all operations on it by simultaneously keeping a count of 0s and 1s in it. But the flip operation would not be possible in constant time with this approach.
So, instead of 1, we will maintain two strings. One is the original string and the other is the opposite string of the original string (i.e. at the positions of 0s, we will keep 1s and vice-versa). In flip operation, we can simply swap the 2 strings.
Following is the implementation for the above approach :
number of ones in our bitset are: 4 Value of our bitset is: 11011