Skip to content

Commit dc35f03

Browse files
committed
src/bin/design-bitset.rs
1 parent fa5e329 commit dc35f03

File tree

1 file changed

+102
-0
lines changed

1 file changed

+102
-0
lines changed

src/bin/design-bitset.rs

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
#![allow(dead_code, unused, unused_variables, non_snake_case)]
2+
3+
fn main() {}
4+
5+
struct Solution;
6+
7+
/**
8+
* `&self` means the method takes an immutable reference.
9+
* If you need a mutable reference, change it to `&mut self` instead.
10+
*/
11+
12+
/**
13+
* Your Bitset object will be instantiated and called as such:
14+
* let obj = Bitset::new(size);
15+
* obj.fix(idx);
16+
* obj.unfix(idx);
17+
* obj.flip();
18+
* let ret_4: bool = obj.all();
19+
* let ret_5: bool = obj.one();
20+
* let ret_6: i32 = obj.count();
21+
* let ret_7: String = obj.to_string();
22+
*/
23+
24+
struct Bitset {
25+
data: Vec<u8>,
26+
size: i32,
27+
count: i32,
28+
}
29+
30+
impl Bitset {
31+
fn new(size: i32) -> Self {
32+
Self {
33+
data: vec![0; size as usize / 8 + 1],
34+
size,
35+
count: 0,
36+
}
37+
}
38+
39+
fn set(&mut self, idx: usize, val: u8) {
40+
let index = idx / 8;
41+
let n = idx % 8;
42+
if val == 1 {
43+
let d = 0b1 << (7 - n);
44+
if self.data[index] != self.data[index] | d {
45+
self.count += 1;
46+
self.data[index] = self.data[index] | d;
47+
}
48+
} else {
49+
let d = 0b11111111 ^ (0b1 << (7 - n));
50+
if self.data[index] != self.data[index] & d {
51+
self.count -= 1;
52+
self.data[index] = self.data[index] & d;
53+
}
54+
}
55+
}
56+
57+
fn fix(&mut self, idx: i32) {
58+
self.set(idx as usize, 1);
59+
}
60+
61+
fn unfix(&mut self, idx: i32) {
62+
self.set(idx as usize, 0)
63+
}
64+
65+
fn flip(&mut self) {
66+
self.count = self.size - self.count;
67+
68+
for i in 0..self.data.len() {
69+
self.data[i] = !self.data[i];
70+
}
71+
}
72+
73+
fn all(&self) -> bool {
74+
self.count == self.size
75+
}
76+
77+
fn one(&self) -> bool {
78+
self.count > 0
79+
}
80+
81+
fn count(&self) -> i32 {
82+
self.count
83+
}
84+
85+
fn to_string(&self) -> String {
86+
let mut s = String::with_capacity(self.size as usize);
87+
88+
'b: for i in 0..self.data.len() {
89+
for index in 0..8 {
90+
if i * 8 + index >= self.size as usize {
91+
break 'b;
92+
}
93+
if self.data[i] >> (7 - index) & 0b1 == 0b1 {
94+
s.push('1');
95+
} else {
96+
s.push('0');
97+
}
98+
}
99+
}
100+
s
101+
}
102+
}

0 commit comments

Comments
 (0)