您的位置:首页 > 其它

Leetcode: Reverse Bits

2015-04-21 10:55 260 查看
题目:

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?

Related problem: Reverse Integer

思路分析:

从右到左取出每一位的数字,然后从左到右放置!注意位运算的神奇之处!

C++参考代码:

class Solution
{
public:
uint32_t reverseBits(uint32_t n)
{
uint32_t result = 0;
for (int i = 0; i < 32; ++i)
{
result <<= 1;//结果每次先左移一位,这样每次后面的数字 就能向前走一位
if (n & 1) result |= 1;//如果n的末尾是1,则在result的后面修改为1
//其实这里换成result ^= 1也是没问题的,因为0|1=1,0^1=1
n >>= 1;//n右移,用于从右到左每次取后面的数字
}
return result;
}
};


因为C++整形数据所占的字节数会随着机器的不同而稍微有些区别,如果题目没有说明给定的无符号整形是4个字节,32位呢?我们可以通过数字1左移判断无符号整形的字节数。

C++参考代码:

class Solution
{
public:
unsigned int reverseBits(unsigned int n)
{
unsigned int result = 0;
//通过1左移判断无符号整形的字节数
for (int i = 1; i != 0; i <<= 1)
{
result <<= 1;
if (n & 1) result |= 1;
n >>= 1;
}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: