【leetcode】190. Reverse Bits

题目:
Reverse bits of a given 32 bits unsigned integer.


思路:
设置两个变量left_mask和right_mask,分别获取二进制左、右两端的bit。然后相向而行、逐位比较就可以啦。


代码实现:

class Solution {
public:
    uint32_t reverseBits(uint32_t n) {
        uint32_t left_mask = 0x80000000;
        uint32_t right_mask = 0x00000001;
        
        while (left_mask > right_mask){
            uint32_t t1 = n & left_mask;
            uint32_t t2 = n & right_mask;
            if (t1 == 0){
                n &= ~right_mask;
            }else{
                n |= right_mask;
            }
            if (t2 == 0){
                n &= ~left_mask;
            }else{
                n |= left_mask;
            }
            left_mask >>= 1;
            right_mask <<= 1;
        }
        
        return n;
    }
};

原创文章 299 获赞 2 访问量 1万+

猜你喜欢

转载自blog.csdn.net/zxc120389574/article/details/106026294