您的位置:首页 > 其它

Leetcode NO.190 Reverse Bits

2015-03-13 23:43 323 查看
题目要求如下:

Reverse bits of a given 32 bits unsigned integer.

For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as00111001011110000010100101000000).

Follow up:

If this function is called many times, how would you optimize it?

Related problem: Reverse Integer
没太关注follow,主要是没太明白啥意思。。就把前面的做了。。不是很喜欢这种bit manipulation的题目。。。
我的解决方法就是每次从原数取最后一位,放在新数的末尾。。。下次迭代新数左移一位,原数右移一位,重复同样操作

代码如下:

class Solution {
public:
    uint32_t reverseBits(uint32_t n) {
        uint32_t res = 0;
        int cnt = 32;
        while (cnt--) {
        	res <<= 1;
        	res += (n & 1);
        	n >>= 1;
        }
        return res;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: