Math Fundamentals18 sections · 814 units
Open in Course

Reverse Bits - Implementation

Pseudocode solution

Here is the complete solution:


function reverseBits(n)
    result := 0
    for i from 0 to 31
        result := result << 1        // Shift result left
        result := result | (n & 1)   // Add rightmost bit of n
        n := n >> 1                  // Shift n right
    return result

The loop runs exactly 32 times, processing each bit once. Time complexity: O(1)O(1) (constant 32 iterations). Space: O(1)O(1). This pattern of extracting and reassembling bits appears in many problems.