参考:https://leetcode-cn.com/problems/design-bitset/
用C++中stl中自带的bitset做,注意的是bitset得固定申请大小,不能动态在函数中申请,所以在最开始先申请好,之后在求all,one,count的时候要注意处理,即最后一段数是不会被修改的全0或者全1,用标记计算即可。
class Bitset {
public:
bitset<100001>s;
int n,other;
Bitset(int size) {
n=size;
other=100001-size;
}
void fix(int idx) {
s[idx]=1;
}
void unfix(int idx) {
s[idx]=0;
}
void flip() {
s=~s;
}
bool all() {
if(s[100000]==1)return s.count()==s.size();
else return s.count()==n;
}
bool one() {
if(s[100000]==0)return s.any();
else return s.count()>other;
}
int count() {
if(s[100000]==0)return s.count();
else return s.count()-other;
}
string toString() {
string res;
for(int i=0;i<n;i++)res+=s[i]+'0';
return res;
}
};
/**
* 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();
*/