public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int left = 31, right = 0;
while(left > right){
// We must let n take the return value otherwise its value won't change
n = swap(n, left, right);
left--;
right++;
}
return n;
}
private int swap(int n, int left, int right){
int leftBit = (n >> left) & 1;
int rightBit = (n >> right) & 1;
if(leftBit != rightBit){
n ^= ((1 << left) | (1 << right));
}
return n;
}
}
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int y = 0;
for(int i = 0; i < 32; i++){
y = (y << 1) + ((n >> i) & 1);
}
return y;
}
}