Reverse Bits
Problem Statement
Take the 32 bits of n and put them in the opposite order. Bit 0 moves to position 31, bit 1 moves to position 30, and so on. Return the number that the reversed bits form.
Follow-up: if this function is called many times, how would you speed it up?
An integer n, written in 32 bits (leading zeros count).
The integer formed by the 32 reversed bits.
In 32 bits, 43261596 is 00000010100101000001111010011100. Reversed, it is 00111001011110000010100101000000, which is 964176192.
In 32 bits, it is 01111111111111111111111111111100. Reversed, it is 00111111111111111111111111111110, which is 1073741822.
- β’ 0 β€ n β€ 2^31 β 2
- β’ n is even
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Write 32 characters of 0 and 1, reverse the string, read it back as a number
Read n's bits from the bottom and place each one at the top of res, for exactly 32 steps
Turn n into a 32-character string of 0s and 1s, reverse the string, and parse it back as a binary number. Each step is easy to check by eye.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Bit Manipulation translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.