[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
        
相关推荐
MicroTech20251 分钟前
量子仿真新基石:MLGO微算法科技专用地址生成器驱动量子算法仿真革命
科技·算法·量子计算
WBluuue4 分钟前
数据机构与算法:dp优化——倍增优化
c++·算法·leetcode·动态规划
叫我辉哥e15 分钟前
新手进阶Python:办公看板升级交互式可视化+移动端适配+多终端同步
开发语言·python
m0_561359676 分钟前
Python面向对象编程(OOP)终极指南
jvm·数据库·python
zhangfeng11336 分钟前
deepseek部署和训练的PyTorch CUDA Transformers Accelerate PEFT稳定版本呢推荐
人工智能·pytorch·python
Bruk.Liu9 分钟前
(LangChain实战5):LangChain消息模版ChatPromptTemplate
人工智能·python·langchain·agent
Wiktok10 分钟前
SQLAlchemy+PyMySQL的实用实战示例
python·mysql·sqlalchemy
yufuu9811 分钟前
用Python批量处理Excel和CSV文件
jvm·数据库·python
深蓝电商API14 分钟前
异步爬虫结合 MongoDB 异步驱动 pymongo:高效数据爬取与存储实践
爬虫·python·mongodb
一个网络学徒14 分钟前
python练习3
开发语言·python