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 :
C++
#include <bits/stdc++.h>
using namespace std;
int zero = 0, one = 0, sz = 0;
string s, t;
void init( int size)
{
string ss(size, '0' );
string tt(size, '1' );
t = tt;
s = ss;
zero = size;
sz = size;
}
void fix( int pos)
{
if (s[pos] == '0' ) {
one++;
zero--;
}
t[pos] = '0' ;
s[pos] = '1' ;
}
void unfix( int pos)
{
if (s[pos] == '1' ) {
zero++;
one--;
}
t[pos] = '1' ;
s[pos] = '0' ;
}
void flip()
{
swap(s, t);
swap(one, zero);
}
bool check()
{
return (one == sz);
}
bool checkOne() { return (one > 0); }
int countOne() { return one; }
string Value() { return s; }
int main()
{
init(5);
fix(1);
fix(2);
unfix(1);
flip();
int number_of_ones = countOne();
string bitset = Value();
cout << "number of ones in our bitset are: "
<< number_of_ones << endl;
cout << "Value of our bitset is: " << bitset << endl;
}
|
Output
number of ones in our bitset are: 4
Value of our bitset is: 11011
Last Updated :
28 Mar, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...