Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).
python代码
class Solution:
# @param n, an integer
# @return an integer
def reverseBits(self, n):
m = 1 << 31;
k = 1;
ans = 0;
for i in range(32):
if m & n:
ans |= k;
m >>= 1;
k <<= 1;
return ans;
java代码
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int ans = 0;
for(int i = 0; i < 32; i++){
if((n & 1) == 1){
ans |= 1;
}
//ans = ans + (n & 1);
n >>= 1;
if(i != 31){
ans <<= 1;
}
}
return ans;
}
}