Reverse Bits

Easybit-manipulation
Category: Bit Manipulation
Companies that ask this question:
AmazonAppleFacebook

Approach

Reverse Bits

Approach

Use bit manipulation to reverse the 32-bit representation.

Algorithm

  1. Initialize result to 0
  2. For each of 32 positions:
    • Extract rightmost bit of n using (n & 1)
    • Shift result left by 1 position
    • Add extracted bit to result
    • Shift n right by 1 position
  3. Return reversed result

Complexity

  • Time: O(1) - fixed 32 iterations
  • Space: O(1) - constant space

Key Insights

  • Process bits from right to left of input
  • Build result from left to right
  • Use bitwise operations: & (AND), << (left shift), >> (right shift), | (OR)

Solution

java
1public class Solution {
2    public int reverseBits(int n) {
3        int result = 0;
4        
5        for (int i = 0; i < 32; i++) {
6            // Get the rightmost bit of n
7            int bit = n & 1;
8            // Shift result left and add the bit
9            result = (result << 1) | bit;
10            // Shift n right to process next bit
11            n >>>= 1;
12        }
13        
14        return result;
15    }
16}
Loading visualizer...