【python】Leetcode每日一题-颠倒二进制位


【python】Leetcode每日一题-颠倒二进制位

【题目描述】

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

示例1:

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

示例2:

输入:11111111111111111111111111111101
输出:10111111111111111111111111111111
解释:输入的二进制串 11111111111111111111111111111101 表示无符号整数 4294967293,
     因此返回 3221225471 其二进制表示形式为 10111111111111111111111111111111 。

【分析】

  • 思路

    自己的思路比较老化,普通位运算,真·一位一位得算。

  • AC代码

    class Solution:
        def reverseBits(self, n: int) -> int:
            s = 0
            for k in range(32):
                s = (s << 1) + (n&1)
                n = n >> 1
            return s
    
  • 分治法

    class Solution:
        # @param n, an integer
        # @return an integer
        def reverseBits(self, 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;
    

    举一反三