Reverse Bits
Easy · Bit manipulation
Jump to codeReverse the order of all 32 bits in an unsigned 32-bit integer and return the resulting unsigned value. Leading zeros participate.
Examples
Example 1
n = 43261596
Output: 964176192
Example 2
n = 4294967293
Output: 3221225471
Constraints
- 0 <= n <= 2^32 - 1; reverse all 32 bit positions, including leading zeros.
Need a hint?
Build the answer from the input’s least significant bit.
Real bit manipulation interview questions
Questions on the same topic that candidates reported from real company interviews. Some company questions are locked and open with Premium or XP.
- Maximize the Bitwise AND of K Elements After Spending an Increment BudgetAmazon
- Implement IPv4 iterators and CIDR expansionOpenAI
- Implement firewall matching with CIDR rulesDatabricks
Solution approach
Repeat exactly 32 times: shift the result left, append the input’s lowest bit, then shift the input right using unsigned semantics. Mask to 32 bits if the language uses unbounded integers. Convert a signed bitwise result to unsigned before returning.
Complexity
O(32), hence O(1), time and O(1) space.
Python reference solution
def reverseBits(n):
answer = 0
for _ in range(32):
answer = (answer << 1) | (n & 1)
n >>= 1
return answer
JavaScript solution
function reverseBits(n) {
let answer = 0;
for (let i = 0; i < 32; i++) {
answer = ((answer << 1) | (n & 1)) >>> 0;
n = n >>> 1;
}
return answer;
}
Java solution
import java.util.*;
class Solution {
public long reverseBits(long n) {
long answer = 0;
for (int i = 0; i < 32; i++) {
answer = (answer << 1) | (n & 1);
n >>>= 1;
}
return answer;
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
long long reverseBits(long long n) {
long long answer = 0;
for (int i = 0; i < 32; i++) {
answer = (answer << 1) | (n & 1);
n >>= 1;
}
return answer;
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 6 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[ 43261596 ]
964176192
[ 4294967293 ]
3221225471
[ 0 ]
0
[ 1 ]
2147483648
[ 4294967295 ]
4294967295
Drafts are saved per language in this browser when storage is available.