Reverse Bits
Easy About 10 min Free, no account needed
Reverse a 32-bit pattern - signed shifts will betray you.
The brief
Given a value n in 0..4294967295 (an unsigned 32-bit pattern, passed as a
long), return the value whose 32 bits are in reverse order.
Cramming the value into an int makes the top bit a sign bit, and a signed
right shift drags ones in from the left forever. The visible tests stay below
2^31; the hidden ones do not, so an int-based solution gives the wrong answer.
You will need to keep the work on an unsigned-safe long across all 32 bit
positions.
Starter code
using System;
public class Solution
{
// TODO: return the 32-bit pattern of n, reversed.
public long ReverseBits(long n)
{
throw new NotImplementedException();
}
}How it is graded
Visible examples help you iterate. Hidden tests then cover edge cases and larger inputs, and every test reports server-measured time and allocated bytes.
What it practices
- Bit manipulation
- Use masks, shifts and XOR on the binary representation directly.
Related katas
- Counting Bits Easy Free Popcounts for 0..n - reuse the table you are already building.
- Power of Two Easy Free One bit trick, two edge cases waiting to bite.
- Single Number Easy Free One value appears an odd number of times - XOR finds it for free.
- Gray Code at an Index Medium Free The n-th Gray code without generating the first n-1.