使用 String 实现 C++ Bitset
让我们在 C++ 中实现 bitset,以便可以在规定的时间复杂度内执行以下操作:
- init(int size):初始化一个大小为 0 位的位集。
- void fix(int pos):将位置pos的位更改为 1。如果它已经是 1,则不更改。
- void unfix(int pos):将位置pos处的位更改为 0。如果它已经为 0,则不更改。
- void flip():将所有 1 更改为 0,将所有 0 更改为 1。
- bool check() :如果 bitset 的所有值都是 1 ,则返回 true ,否则返回 false 。
- bool checkOne() :如果至少一位为 1 ,则返回 true。否则返回假。
- int countOne() :返回值为 1 的位数。
- 字符串 Value():以字符串形式返回 bitset 的当前值。
init(size) 必须具有 O(size) 复杂度(大约)。其余操作必须具有恒定的复杂性。
O(size/d) 其中 d 可以是 32 或 64(取决于位)。
实现:通过维护一个给定大小的字符串并通过同时在其中保持 0 和 1 的计数对其执行所有操作,可以轻松完成所需的实现。但是用这种方法不可能在恒定时间内进行翻转操作。
因此,我们将保留两个字符串,而不是 1。一个是原始字符串,另一个是原始字符串的相反字符串(即在 0 的位置,我们将保留 1,反之亦然)。在翻转操作中,我们可以简单地交换 2 个字符串。
以下是上述方法的实现:
C++
// C++ code for the above approach
#include
using namespace std;
// initializing variables to store
// the number of 0s , 1s and size of
// out bitset
int zero = 0, one = 0, sz = 0;
// string "s" is the string to store
// our bitset, string "t" is the
// helper string to make flip()
// function complexity O(1)
string s, t;
// function to initialize the bitset
// of size "size"
void init(int size)
{
string ss(size, '0');
string tt(size, '1');
t = tt;
s = ss;
// initially number of zeroes in
// string s is equal to size
zero = size;
sz = size;
}
// function to make bit at position
//"pos" equal to 1
void fix(int pos)
{
// setting bit at position "pos"
// equal to 1 in string s and equal
// to 0 in string t and simultaneously
// updating
// number of 0s and 1s in string s
if (s[pos] == '0') {
one++;
zero--;
}
t[pos] = '0';
s[pos] = '1';
}
// function to make bit at position "pos"
// equal to 0
void unfix(int pos)
{
// setting bit at position "pos" equal
// to 0 in string s and equal to 1 in
// string t and simultaneously
// updating
// number of 0s and 1s in string s
if (s[pos] == '1') {
zero++;
one--;
}
t[pos] = '1';
s[pos] = '0';
}
// function to flip the bits of bitset
void flip()
{
// for flip operation , we will simply
// swap the strings s and t as they are
// just opposite of each other. Also,
// we will swap number of 0s and 1s in
// string s obviously
swap(s, t);
swap(one, zero);
}
// function to check if all the elements of
// bitset are '1'
bool check()
{
// If number of 1s in string s is equal
// to the size of s, that means all the
// characters of s are 1.
return (one == sz);
}
// function for checking if there is atleast
// one '1' in bitset
bool checkOne() { return (one > 0); }
// function for returning the number of 1s
// in bitset
int countOne() { return one; }
// function for returning value of string s
// or the bitset
string Value() { return s; }
int main()
{
init(5); // 00000
fix(1); // 01000
fix(2); // 01100
unfix(1); // 00100
flip(); // 11011
int number_of_ones = countOne(); // 4
string bitset = Value(); // 11011
cout << "number of ones in our bitset are: "
<< number_of_ones << endl;
cout << "Value of our bitset is: " << bitset << endl;
}
输出
number of ones in our bitset are: 4
Value of our bitset is: 11011