190. Reverse Bits (Int; Bit)

时间:2025-04-08 19:07:43

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) {
uint32_t ret = ; //NOTE: integer got from this way should be decalred as unsigned
int tmp;
/*把一个unsigned int 数字1一直左移,直到它变成全0的时候,也就得到了该机器内unsigned int的长度*/
for (i = ; i != ; i <<= )
tmp = n & 0x1;
n >>= ;
ret <<= ; //must before the operation |
ret |= tmp;
}
return ret;
}
};