Skip to content
Katabench
Try free

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.

The hidden trap

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

C#
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.

C# coding challenges →

What it practices

Bit manipulation
Use masks, shifts and XOR on the binary representation directly.

Related katas