LeetCode 190. Reverse Bits 颠倒二进制位

题目链接:点击这里
在这里插入图片描述
在这里插入图片描述

class Solution {
public:
    uint32_t reverseBits(uint32_t n) {
        uint32_t ans = 0;
        for(int i = 0 ; i < 32; i++) {
            ans <<= 1;  //ans左移一位空出位置
            //ans += (n & 1); //得到的最低位加过来
            ans |= (n & 1);
            n >>= 1;    //原数字右移一位去掉已经处理过的最低位
        }
        return ans;
    }
};

下述具有特殊二进制的整数,可以很方便进行位操作,而且该整数的十六进制形式比较好记,也不用写那么多的0、1:

0xaaaaaaaa = 10101010101010101010101010101010 (偶数位为1,奇数位为0)

0x55555555 = 1010101010101010101010101010101 (偶数位为0,奇数位为1)

0x33333333 = 110011001100110011001100110011 (1和0每隔两位交替出现)

0xcccccccc = 11001100110011001100110011001100 (0和1每隔两位交替出现)

0x0f0f0f0f = 00001111000011110000111100001111 (1和0每隔四位交替出现)

0xf0f0f0f0 = 11110000111100001111000011110000 (0和1每隔四位交替出现)

更简洁的高赞代码如下:

class Solution {
public:
    uint32_t reverseBits(uint32_t n) {
        n = (n >> 16) | (n << 16);
        n = ((n & 0xff00ff00) >> 8) | ((n & 0x00ff00ff) << 8);
        n = ((n & 0xf0f0f0f0) >> 4) | ((n & 0x0f0f0f0f) << 4);
        n = ((n & 0xcccccccc) >> 2) | ((n & 0x33333333) << 2);
        n = ((n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1);
        return n;
    }
};
发布了690 篇原创文章 · 获赞 103 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/qq_42815188/article/details/104059893
今日推荐