190. 颠倒二进制位

190. 颠倒二进制位

1.题目

在这里插入图片描述

2.我的解决方案

  • 一种笨办法
class Solution:
    def reverseBits(self, n: int) -> int:
        binary = list(bin(n))
        binary.pop(0)
        binary.pop(0)   # 去除前缀
        for i in range(32-len(binary)): # 将转换过程中缺失的0补齐
            binary.insert(0, '0')
        binary = binary[::-1]   # 倒置
        binary = "".join(binary)    # 形成字符串
        res = 0
        for i in range(len(binary)):    # 还原成数字
            res = res*2 + int(binary[i])
        return res
  • 时间复杂度: O ( n ) O(n) O(n)
  • 空间复杂度: O ( n ) O(n) O(n)

3.官方的解决方案

class Solution:
    def reverseBits(self, n: int) -> int:
        # 采用简单的位运算就可以完成
        # 瞬间感觉写出的是没有智商的人写出的东西
        res = 0
        for i in range(32):
            res = (res<<1) + (n&1)	# 注意,移位是1不是2
            n >>= 1
        return res
  • 时间复杂度: O ( l o g n ) O(logn) O(logn)
  • 空间复杂度: O ( 1 ) O(1) O(1)

4.拓展

  • 此代码运行不通,当作伪代码来看
  • 思路:点击查看
class Solution:
    def reverseBits(self, n: int) -> int:
        # 使用分治法
        # 位运算的操作秀到我
        """
        1.抽取
        2.移位
        3.相或
        """
        # 间隔一位抽取
        xaaaaaaaa = 1010 1010 1010 1010 1010 1010 1010 1010
        x55555555 = 0101 0101 0101 0101 0101 0101 0101 0101

        # 间隔两位抽取
        xcccccccc = 1100 1100 1100 1100 1100 1100 1100 1100
        x33333333 = 0011 0011 0011 0011 0011 0011 0011 0011

        # 间隔四位抽取
        xf0f0f0f0 = 1111 0000 1111 0000 1111 0000 1111 0000 
        x0f0f0f0f = 0000 1111 0000 1111 0000 1111 0000 1111

        # 间隔八位抽取
        xff00ff00 = 1111 1111 0000 0000 1111 1111 0000 0000
        x00ff00ff = 0000 0000 1111 1111 0000 0000 1111 1111

        n = ((n&xaaaaaaaa)>>1) | ((n&x55555555)<<1)
        n = ((n&xcccccccc)>>2) | ((n&x33333333)<<2)
        n = ((n&xf0f0f0f0)>>4) | ((n&x0f0f0f0f)<<4)
        n = ((n&xff00ff00)>>8) | ((n&x00ff00ff)<<8)
        return n>>16 | n << 16
  • 运行成功的代码
class Solution:
    def reverseBits(self, n: int) -> int:
        # 使用分治法
        # 位运算的操作秀到我
        """
        1.抽取
        2.移位
        3.相或
        """
        n = ((n&0xaaaaaaaa)>>1) | ((n&0x55555555)<<1)
        n = ((n&0xcccccccc)>>2) | ((n&0x33333333)<<2)
        n = ((n&0xf0f0f0f0)>>4) | ((n&0x0f0f0f0f)<<4)
        n = ((n&0xff00ff00)>>8) | ((n&0x00ff00ff)<<8)
        n = ((n&0xffff0000)>>16) | ((n&0x0000ffff)<<16)
        return n
  • 时间复杂度: O ( 1 ) O(1) O(1)
  • 空间复杂度: O ( 1 ) O(1) O(1)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值