Reverse the bits of a number
Easy TimeO(width) SpaceO(1)
Given a number n and a bit width, reverse the order of its bits within that width. Reversing 13 within 8 bits turns 00001101 into 10110000, which is 176. The width counts bit positions up from the lowest; anything above it is ignored, and zeros inside it are bits like any other and take part in the reversal.
Examples
Example 1
- Input
- n = 13width = 8
- Output
17600001101reversed is10110000—128 + 32 + 16= 176.
Example 2
- Input
- n = 13width = 4
- Output
- The same 13, but
111101within 4 bits reverses to1011= 11. The width changes the answer.
The Code
function reverseBits(n, width) {
let result = 0;
for (let i = 0; i < width; i++) {
const bit = (n >>> i) & 1;
result = (result << 1) | bit;
}
return result;
}
reverseBits(13, 8);Done