Practice › Bit Manipulation
Reverse Bits
Easy · Bit Manipulation · Asked at Apple, Amazon, Microsoft, Qualcomm
Treat each number as an unsigned 32-bit integer and reverse the order of its 32 bits (bit 0 becomes bit 31, and so on). Print the result as an unsigned decimal number.
Input
First line: q. Next q lines: one number x each.
Output
q lines — the reversed numbers.
Constraints
- 1 ≤ q ≤ 10^4
- 0 ≤ x < 2^32
Repeat 32 times: shift the result left by one and append the lowest bit of x, then shift x right. Use an unsigned or 64-bit type so the top bit does not make the number negative.
Example 1
Input
2 43261596 4294967293
Output
964176192 3221225471
Hints
- Take bits from the low end of x and push them into the low end of the result.
- After 32 steps the first bit taken has moved to the top.
- The result can be ≥ 2^31 — keep it unsigned or in a 64-bit type.
Approach
Repeat 32 times: result = (result << 1) | (x & 1); x >>= 1. Bit 0 of x is shifted left 31 times in total and ends at bit 31, bit 1 ends at bit 30, and so on. In C++ use uint32_t; in Java use long and mask with 0xFFFFFFFFL; Python integers never overflow.
Complexity: O(32) per number
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int q;
cin >> q;
while (q--) {
unsigned long long v;
cin >> v;
uint32_t x = (uint32_t) v, res = 0;
for (int i = 0; i < 32; i++) {
res = (res << 1) | (x & 1);
x >>= 1;
}
cout << res << "\n";
}
return 0;
}Python solution
import sys
data = list(map(int, sys.stdin.read().split()))
out = []
for x in data[1 : 1 + data[0]]:
res = 0
for _ in range(32):
res = (res << 1) | (x & 1)
x >>= 1
out.append(res)
print("\n".join(map(str, out)))Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int q = Integer.parseInt(br.readLine().trim());
StringBuilder sb = new StringBuilder();
for (int t = 0; t < q; t++) {
long x = Long.parseLong(br.readLine().trim()), res = 0;
for (int i = 0; i < 32; i++) {
res = ((res << 1) | (x & 1)) & 0xFFFFFFFFL;
x >>= 1;
}
sb.append(res).append('\n');
}
System.out.print(sb);
}
}