Reverse Bits

Reverse the bits of a 32-bit unsigned integer.

A way to picture it

Deal a deck of cards from the top of one pile onto a new pile, one at a time — the new pile comes out reversed. Here the deck is 32 bits: pop the last bit off n and push it onto the end of result.

How to approach it

32 times: result = (result << 1) | (n & 1), then n >>>= 1.

Example

Input: {"n":43261596}. Output: 964176192.

Complexity: O(1) time and O(1) space. Always exactly 32 iterations.

This page includes an animated walkthrough, Java and Python solutions, and a question to check your understanding.