Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions reverse-bits/yhkee0404.rs
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 << 6 = 64개 만큼의 전처리 시간과 공간을 희생해서 추론 시간을 32번에서 6번으로 줄였습니다.
Bucket 또는 Square Root Decomposition이라고 할 수 있겠어요: https://github.com/DaleStudy/leetcode-study/pull/1792/files#r2265196896

Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
use std::sync::OnceLock;

static _TABLE: OnceLock<Vec<i32>> = OnceLock::new();

impl Solution {

pub fn reverse_bits(mut n: i32) -> i32 {
let mut x = 0;
for i in 0..6 {
let shift = if i == 5 {2} else {6};
x = x << shift | Self::init_table()[(n & (1 << shift) - 1) as usize] >> 6 - shift;
n >>= 6;
}
x as i32
}

fn init_table() -> &'static Vec<i32> {
_TABLE.get_or_init(|| {
let mut table: Vec<i32> = vec![0; 1 << 6];
for (i, x) in table.iter_mut().enumerate() {
let mut j = i as i32;
for k in 0..6 {
*x = *x << 1 | j & 1;
j >>= 1;
}
}
table
})
}

}