LeetCode Reverse Bits 的C++解决4ms

最开始想到的是先把无符号数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-该位的位置)。

发布了50 篇原创文章 · 获赞 7 · 访问量 6万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章