LeetCode Entry
190. Reverse Bits
Reverse bits
190. Reverse Bits easy blog post substack youtube

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/1271
Problem TLDR
Reverse bits #easy #bits
Intuition
Manually reverse all 31 positions.
Approach
- if called many times: use built-in functions (they should be optimized and cached) and use lookup tables if memory allows
Complexity
-
Time complexity: \(O(log(n))\)
-
Space complexity: \(O(1)\)
Code
// 103ms
fun reverseBits(n: Int) =
Integer.reverse(n)
/*
(0..31).sumOf { b -> n shr b and 1 shl (31-b) }
n.toString(2).reversed().padEnd(32,'0').toInt(2)
(0..31).fold(0) { r, b -> n shr b and 1 shl (31-b) or r }
*/
// 2ms
pub const reverse_bits: fn(i32) -> i32 = i32::reverse_bits;
/*
pub fn reverse_bits(n: i32) -> i32 {
(0..32).map(|b| (n >> b & 1) << (31-b)).sum()
}
*/