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
- n is a 32-bit unsigned integer: 0 ≤ n ≤ 2³² − 1
- All 32 bits count, including leading zeros
Edge cases to test
- n = 0
- All ones
- Only the lowest bit set
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++ useuint32_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 resultC++
#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
- Rotate Image (Medium)
- Spiral Matrix (Medium)
- Set Matrix Zeroes (Medium)
- Search a 2D Matrix (Medium)
- Search a 2D Matrix II (Medium)
- Valid Sudoku (Medium)
- Single Number (Easy)
- Single Number II (Medium)
- Single Number III (Medium)
- Number of 1 Bits (Easy)
- Counting Bits (Easy)
- Missing Number (Easy)
- Sum of Two Integers (Medium)
- Power of Two (Easy)