[LeetCode] 颠倒二进制位

颠倒给定的 32 位无符号整数的二进制位。

示例:

输入: 43261596
输出: 964176192
解释: 43261596 的二进制表示形式为 00000010100101000001111010011100 ,
     返回 964176192,其二进制表示形式为 00111001011110000010100101000000 

进阶:
如果多次调用这个函数,你将如何优化你的算法?

class Solution {
public:
    uint32_t reverseBits(uint32_t n) {
        uint32_t res= 0;
        for(int i=0;i<32;i++)
        {
            if(n & 1 == 1)
                res = (res<<1)+1;
            else
                res = res<<1;
            n = n >> 1;
            
        }
        
        return res;
    }
};
class Solution {
public:
    uint32_t reverseBits(uint32_t n) {
       uint32_t res = 0;
       int i = 0;
       while(i<32)
       {
           uint32_t temp = n & 0x01;
           res = (res<<1) | temp;
           i++;
           n =  n>>1;           
       }
        
       return res;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_37992828/article/details/82746846