[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
        
相关推荐
专注仿真12 分钟前
仿真智能体训练(评估篇):鲁棒性/泛化测试算法详解与实战
人工智能·python·算法·afsim智能体训练·评估算法·鲁棒性算法·泛化测试算法
纪念 22913 分钟前
C++ 算法模板与错题 模拟(一)
android·c++·算法
SummerJokes33 分钟前
Java 集合 List 全套实验|从基础增删改查到实体类存储
java·python·list
电科_银尘35 分钟前
【大模型算法与工程 51】检索基础:Embedding、向量索引与BM25
算法·机器学习·embedding
空堂与归1 小时前
2026-12-02_Anthropic格密码银河级算法
人工智能·算法·ai·密码学
蓝色汪洋1 小时前
qsort使用指南
数据结构·算法
车软学堂1 小时前
Docker在隔离什么:namespace、cgroup、chroot三道墙
linux·python·docker·容器·车载系统·汽车·测试用例
大熊背1 小时前
海思 ISP 光圈控制(AI / DC-Iris / P-Iris)详解
算法·自动曝光·曝光路径
zhanghongyi_cpp2 小时前
第4章 学习自测
python·学习
李松桃2 小时前
Python爬虫基础
开发语言·爬虫·python·get请求使用方法·post请求使用方法