LeetCode. 颠倒二进制位

题目要求:

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

示例:

输入: 00000010100101000001111010011100
输出: 00111001011110000010100101000000
解释: 输入的二进制串 00000010100101000001111010011100 表示无符号整数 43261596,
因此返回 964176192,其二进制表示形式为 00111001011110000010100101000000。

代码:

class Solution {
public:
    uint32_t reverseBits(uint32_t n) {
        uint32_t result = 0;
        for(int i = 0; i < 32; i++) {
            result <<= 1;
            result = result | (n & 1);
            n >>= 1;
        }
        return result;
    }
};

分析:

会对二进制数末尾进行赋值

猜你喜欢

转载自www.cnblogs.com/leyang2019/p/11688987.html