[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
        
相关推荐
姜鱼问生18 分钟前
fail2ban 实战:从默认配置到生产可用
后端·算法·架构
垆边人似月.24 分钟前
华为题:全排列
算法·深度优先·图论
czq_268671948726 分钟前
Python打卡第36天
pytorch·python·深度学习
计算机编程指导师29 分钟前
【计算机毕设】基于Hadoop+Spark的美国互联网银行贷款数据可视化分析系统源码 毕业设计 选题推荐 毕设选题 数据分析 机器学习
大数据·hadoop·python·数据分析·spark·毕业设计·贷款
杜 硕33 分钟前
快速排序详解01
数据结构·算法·排序算法
Starry-sky(jing)44 分钟前
onnxruntime 安装后 GPU 没加速?3 条命令确认它跑在 CPU 还是 GPU
python·gpu·cuda·onnxruntime·推理加速
步行cgn1 小时前
Spring AOP 实战:安全日志
python·安全·spring
Matlab程序猿1 小时前
【MATLAB源码-第459期】基于matlab的D-H模型与阻尼最小二乘逆运动学的六自由度机械臂五次轨迹规划及动力学前馈PD控制仿真。
人工智能·算法·matlab·d-h建模·六自由度串联机械臂
信奥卷王1 小时前
[GESP202606 六级] 满二叉树
数据结构·算法
诺伦1 小时前
OpenAI Agents API 公测拆解:托管编排+持久会话+自有沙箱搭一条自动增长流水线 | RiseClaw玄策
python·openai·ai agent·营销自动化·agent编排