[NeetCode 150] Reverse Bits

Reverse Bits

Given a 32-bit unsigned integer n, reverse the bits of the binary representation of n and return the result.

Example 1:

复制代码
Input: n = 00000000000000000000000000010101

Output:    2818572288 (10101000000000000000000000000000)

Explanation: Reversing 00000000000000000000000000010101, which represents the unsigned integer 21, gives us 10101000000000000000000000000000 which represents the unsigned integer 2818572288.

Solution

We can convert the number into a binary number and store its bits, then sum up the bits in reverse order.

Or actually we don't need to store the bits, as we've already known where the bit will be after reversion.

Code

Convert and store:

py 复制代码
class Solution:
    def reverseBits(self, n: int) -> int:
        bits = []
        while n > 0:
            bits.append(n%2)
            n //= 2
        
        while len(bits) < 32:
            bits.append(0)

        ans = 0
        for bit in bits:
            ans <<= 1
            ans += bit
        
        return ans
        

No store:

py 复制代码
class Solution:
    def reverseBits(self, n: int) -> int:
        ans = 0
        for i in range(32):
            bit = (n >> i) & 1
            ans += bit<<(31-i)
        return ans
        
相关推荐
机器人零零壹3 小时前
技术白皮书:iRobotCAM如何解决机器人激光切割应用中的核心难点,从CAD离线编程到双目视觉定位与轨迹自适应提升复杂空间曲线切割的精度、效率与柔性化水平
人工智能·算法
belldeep5 小时前
python:genesis-world, Genesis-Embodied-AI
人工智能·python·ai·genesis
benchmark_cc5 小时前
A 股、港股、美股如何建立统一的标的主数据格式?
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
ZhengEnCi6 小时前
大模型的分类到底怎么分:从基础模型到推理模型、从通用到专用的完整图谱
算法
维克兜率天6 小时前
【维克】趋势型CTA:期货市场的“追涨杀跌“
人工智能·python
取名真是7 小时前
Python 算法知识点从基础到进阶
开发语言·python·算法
梦想不只是梦与想7 小时前
PyTorch、CPU、GPU、CUDA
人工智能·pytorch·python·深度学习·机器学习·cuda
数字融合7 小时前
透明化视频孪生危化安全管控解决方案
人工智能·python·安全
罗西的思考7 小时前
【轻量化复刻大模型 / KIMI K3】KDA 模块交互式演示
人工智能·算法·机器学习
别问!问就是全会9 小时前
Jupyter Notebook 安装包下载|单元格分块运行,图表直接内嵌
ide·python·其他·jupyter