LeetCode ยท #190

Reverse Bits Solution

Reverse all 32 bits of the given unsigned integer.

01
Section One ยท Problem

Problem Statement

๐Ÿท๏ธ

Difficulty

Easy

๐Ÿ”—

LeetCode

Problem #190

๐Ÿ—๏ธ

Pattern

Bit Manipulation โ€” extract & place

Example
Input: n = 43261596 // 00000010100101000001111010011100 Output: 964176192 // 00111001011110000010100101000000
02
Section Two ยท Approach 1

String Conversion โ€” O(32)

Convert to 32-bit binary string, reverse it, parse back. Works but not bit-level elegant.

Better: Extract LSB with n & 1, shift result left, OR the bit in, shift n right. 32 iterations.
03
Section Three ยท Approach 2

Bit-by-Bit Reversal โ€” O(32) = O(1)

Extract the LSB of n, place it at the MSB position of the result. Shift n right, shift result left, repeat 32 times.

๐Ÿ’ก Mental model: Imagine reading a word backwards letter by letter. Take the last letter of n, append it to result. Remove that letter from n. After 32 letters, result is the reversed word.
๐ŸŽฏ Pattern: "Reverse bits of an integer." The shift-extract-place loop is the standard approach. For repeated calls, precompute a byte-reversal table for O(1) lookups (divide-and-conquer on bytes).
04
Section Four ยท Trace

Visual Walkthrough

Reverse Bits โ€” LSB to MSB
Loop 32 times: result = (result << 1) | (n & 1); n >>>= 1; Iter 1: n LSB = 0, result = 0. Iter 2: n LSB = 0, result = 0. ... After 32 iterations, all bits reversed. Result = 964176192. return 964176192 โœ“
05
Section Five ยท Implementation

Code โ€” Java & Python

Java
class Solution { public int reverseBits(int n) { int res = 0; for (int i = 0; i < 32; i++) { res = (res << 1) | (n & 1); n >>>= 1; } return res; } }
Python
class Solution: def reverseBits(self, n: int) -> int: res = 0 for _ in range(32): res = (res << 1) | (n & 1) n >>= 1 return res
06
Section Six ยท Analysis

Complexity Analysis

ApproachTimeSpace
Bit-by-bitO(1) (32 ops)O(1)
07
Section Seven ยท Edge Cases

Edge Cases & Pitfalls

CaseInputWhy It Matters
Zero0Reversed = 0.
All ones0xFFFFFFFFReversed = 0xFFFFFFFF.
Power of 210...01 โ†’ 10...0 = 2ยณยน.
โš  Common Mistake: Forgetting to loop exactly 32 times. Stopping when n becomes 0 loses leading zeros โ€” which become trailing zeros in the reversed result. Always iterate all 32 bits.

โ† Back to Math & Bit problems