题目:
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).
Follow up: If this function is called many times, how would you
optimize it?
答案:
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
if(n == 0)
return 0;
unsigned int m = 0;
int inum;
for(int i = 0; i<32; ++i){
inum = (1<<i) & n;//得到位置i上的数,从低位到高位0..31;若n中位置i为0,则inum为0,否则inum除了位置i为1,其他位置为0
if(inum != 0) //该条件不能用inum == 1,,得到的仍然是一串二进制数中间一个1或者0
m |= 1 << (31-i);
}
return m;
}
};
结果: