Bit ReversalLoading saved progress…

Bit Reversal

Implement bitReversal(n) that reverses the order of the bits in the binary representation of a non-negative integer n. Use the number's minimal width — the digits you get from n.toString(2), with no leading-zero padding — then read those bits back-to-front and interpret the result as a number. Because the width is minimal, any trailing zeros in n become leading zeros in the reverse and simply disappear.

Signature

// n:       a non-negative integer (its bits come from n.toString(2)).
// returns: the integer you get by reversing those bits and re-reading them.
function bitReversal(n: number): number;

Examples

// 13 is 1101; reversed it is 1011, which is 11.
bitReversal(13); // → 11
// 6 is 110; reversed it is 011 = 11 in binary = 3.
// The trailing zero of 6 becomes a leading zero and vanishes.
bitReversal(6); // → 3

Notes

  • Minimal width, no padding. Operate on n.toString(2) as-is — 6 is '110', three bits, not '00000110'. This differs from the fixed 32-bit reversal some problems ask for.
  • Trailing zeros are lost. When the lowest bits of n are zero, reversing moves them to the front where they carry no value. 8 (1000) reverses to 0001 = 1.
  • Bit-palindromes return themselves. 9 is 1001 and 5 is 101; both read the same forwards and backwards, so the function returns the input unchanged.
  • Edge values. bitReversal(0) is 0 and bitReversal(1) is 1.
  • Non-negative only. You do not need to handle negative numbers or non-integers.
Loading editor…