[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
        
相关推荐
2601_9563198814 小时前
最新AI量化提效,先做可验证的小流程
人工智能·python
KaMeidebaby14 小时前
卡梅德生物技术快报|小 RNA 适配体合成 + 多方法亲和力表征全流程标准化操作手册
前端·网络·数据库·人工智能·算法
是Dream呀14 小时前
基于深度学习的人类行为识别算法研究
人工智能·深度学习·算法
happyprince15 小时前
03_NVIDIA_ModelOpt-量化算法深入
人工智能·深度学习·算法
开飞机的舒克_15 小时前
FastAPI 实战入门:从路由、参数校验到依赖注入的后端开发指南
python·fastapi
大鱼>15 小时前
AI+货物追踪:智能快递柜追踪系统
人工智能·深度学习·算法·机器学习
霸道流氓气质16 小时前
Kiro 中反编译 JAR 包并分析字节码的流程指南
chrome·python·jar
人工智能时代 准备好了吗16 小时前
AI回答内容进入率监测:引用识别、文本匹配与语义判断
开发语言·人工智能·python
researcher-Jiang16 小时前
算法训练:堆 & 可并堆
算法
在书中成长16 小时前
HarmonyOS 小游戏《对战五子棋》开发第18篇 - 棋盘设计
算法·harmonyos