Algo-Sim › Matrix & Bit Manipulation

Reverse Bits

Easy · Matrix & Bit Manipulation · step through it in Java, Python and C++ on your own input

Reverse the 32 bits of an unsigned integer: shift bits off the right of n and onto the right of the result.

Problem

Treat n as a 32-bit unsigned integer and reverse the order of its bits, so bit 0 becomes bit 31 and so on. Return the resulting unsigned value.

Constraints

Edge cases to test

Follow-up questions

If called many times, how do you optimise?
Cache the reverse of each byte (256 entries) and combine four lookups, or swap halves, quarters and so on with masks: O(1) operations.
Why unsigned shifts?
In Java, >> on a negative number shifts in ones; use >>>. In C++ use uint32_t.

Solution

Java

public int reverseBits(int n) {
    int result = 0;
    for (int i = 0; i < 32; i++) {
        result = (result << 1) | (n & 1);
        n >>>= 1;
    }
    return result;
}

Python

def reverse_bits(n):
    result = 0
    for _ in range(32):
        result = (result << 1) | (n & 1)
        n >>= 1
    return result

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    uint32_t reverseBits(uint32_t n) {
        uint32_t result = 0;
        for (int i = 0; i < 32; i++) {
            result = (result << 1) | (n & 1);
            n >>= 1;
        }
        return result;
    }
};

More Matrix & Bit Manipulation problems