LeetCode Reverse Bits 的C++解决4ms

来源:互联网 发布:拳皇98um优化版 编辑:程序博客网 时间:2024/06/11 17:13

最开始想到的是先把无符号数n转换成二进制,然后把每一位依次存放到vector容器中,最后在以相反的顺序取出每一位的值换成十进制即可。代码如下:

class Solution {public:    uint32_t reverseBits(uint32_t n) {    int i = 0, index = 0;    vector<int> v;    //auto it = v.begin();    unsigned int res = 0;    if (n == 0)        return 0;    while (i < 32)    {        v.push_back(n % 2);        n /= 2;        i++;    }    for (auto it = v.rbegin(); it != v.rend(); it++)        res += *it * pow(2, index++);    return res;    }};

然后看到Discuss中的用位运算来解决的,只用了4ms。比上面的方法简洁也快速了很多。代码如下:

    uint32_t result = 0;    int bit = 0;    for(int i=0; i<32; i++)    {        bit = n&1;        n = n>>1;        result = 2*result + bit;    }    return result;

因为除2操作就相当于右移一位,从最低位开始,如果该位为1,result += pow(2,32-该位的位置)。

0 0
原创粉丝点击