Leetcode NO.190 Reverse Bits

来源:互联网 发布:画原理图的软件 编辑:程序博客网 时间:2024/06/06 01:57

题目要求如下:

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;    }};


0 0