Reverse Bits
Easy
Topics
Reverse the bits of a given 32-bit unsigned integer. Return the resulting unsigned integer represented as a (possibly large) number.
For example, the input 43261596 in binary is 00000010100101000001111010011100. Reversing gives 00111001011110000010100101000000 which is 964176192.
Example 1
Input: n = 43261596 Output: 964176192
Example 2
Input: n = 4294967293 Output: 3221225471
Example 3
Input: n = 0 Output: 0
Constraints
- 0 <= n <= 2^32 - 1
Editorial — intuition, approach, complexity and pitfalls
Intuition
Reversing a fixed-width bit pattern is a pull-and-push loop: take the lowest bit of the input, shift it into the output from the bottom, and the output accumulates in reverse order. Thirty-two iterations, one per bit, regardless of the value.
The thing to be careful about is that the width is fixed at 32, not determined by the number's magnitude. Reversing 1 must give 2^31, so leading zeros are significant and the loop must run the full 32 times rather than stopping when the input is exhausted.
Approach
out = 0.- Thirty-two times: shift
outleft, OR inn & 1, shiftnright.
Dry Run
n = 13 = ...00001101, shown over 8 bits for brevity
iter n & 1 out so far
1 1 1
2 0 10
3 1 101
4 1 1011
5 0 10110
6 0 101100
7 0 1011000
8 0 10110000
over 8 bits, 00001101 reverses to 10110000
over 32 bits the same loop runs 32 times, so the
24 leading zeros become 24 trailing zerosComplexity
- Time — O(1): exactly 32 iterations, independent of the input. Calling it O(log n) would also be defensible, but the width is fixed so constant is the honest description.
- Space — O(1).
Common Pitfalls
- Stopping the loop when
nbecomes 0. Leading zeros matter, so1would reverse to1instead of2^31. - Using a signed right shift in Java, where
>>sign-extends and loops forever on a negative input. Use>>>. - In Python, forgetting to mask. Python integers are unbounded, so the result is naturally correct here, but anything that shifts
nleft needs& 0xFFFFFFFF. - Building a binary string, reversing it, and parsing it back. Correct and much slower, and it allocates.
- Missing the follow-up: if the function is called many times, cache reversals of byte-sized chunks and compose four lookups.
Full Solution — all languages
class Solution:
def reverseBits(self, n):
out = 0
for _ in range(32):
out = (out << 1) | (n & 1)
n >>= 1
return outimport java.util.*;
class Solution {
public long reverseBits(long n) {
long value = n & 0xFFFFFFFFL;
long out = 0;
for (int i = 0; i < 32; i++) {
out = (out << 1) | (value & 1L);
value >>= 1;
}
return out;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: long long reverseBits(long long n) {
long long value = n & 0xFFFFFFFFLL;
long long out = 0;
for (int i = 0; i < 32; i++) {
out = (out << 1) | (value & 1LL);
value >>= 1;
}
return out;
}
};/**
* @param {number} n
* @return {number}
*/ var reverseBits = function(n) {
let out = 0;
for (let i = 0; i < 32; i++) {
out = (out * 2) + (n & 1);
n >>>= 1;
}
return out;
};