← Back to Leo Academy Masterclass

Problem #190: Reverse Bits

Easy Bit Manipulation

Intuition & Strategy Breakdown

Iterate through 32 bits, shifting result left by 1 and ORing least significant bit of n while right-shifting n by 1.

Python Solution

class Solution:
    def reverseBits(self, n: int) -> int:
        res = 0
        for _ in range(32):
            res = (res << 1) | (n & 1)
            n >>= 1
        return res

Java Solution

public 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;
    }
}
Watch Interactive Video on Leo Academy Main App