Skip to content

Commit bfb5219

Browse files
authored
reverse bits solution
1 parent ca75dba commit bfb5219

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

reverse-bits/yhkee0404.rs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
use std::sync::OnceLock;
2+
3+
static _TABLE: OnceLock<Vec<i32>> = OnceLock::new();
4+
5+
impl Solution {
6+
7+
pub fn reverse_bits(mut n: i32) -> i32 {
8+
let mut x: u32 = 0;
9+
for i in 0..6 {
10+
let shift = if i == 5 {2} else {6} as u32;
11+
x = x << shift | Self::init_table()[(n & (1 << shift) - 1) as usize] as u32 >> 6 - shift;
12+
n >>= 6;
13+
}
14+
x as i32
15+
}
16+
17+
fn init_table() -> &'static Vec<i32> {
18+
_TABLE.get_or_init(|| {
19+
let mut table: Vec<i32> = vec![0; 1 << 6];
20+
for (i, x) in table.iter_mut().enumerate() {
21+
let mut j = i as i32;
22+
for k in 0..6 {
23+
*x = *x << 1 | j & 1;
24+
j >>= 1;
25+
}
26+
}
27+
table
28+
})
29+
}
30+
31+
}

0 commit comments

Comments
 (0)