问题描述:
Reverse bits of a given 32 bits unsigned integer.
示例:
given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).
问题分析:
这个题类似于把一个整数翻转,只不过整数那个对应的是十进制,而本题对应二进制。
过程详见代码:
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t res = 0;
uint32_t flag = 1;
for(int i = 0;i < 32;i++)
{
res = res * 2 + (flag & n);
n = n >> 1;
}
return res;
}
};