[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
        
相关推荐
IT大师兄吖2 分钟前
flux-2-Klein-BFS-换头换脸工作流 懒人整合包
算法·宽度优先
何政@4 分钟前
Agent Skills 完全指南:从概念到自定义实践
人工智能·python·大模型·claw·404 not found 罗
波哥学开发10 分钟前
深入解析 BEV 图像色彩调整与伪彩色映射:从直方图统计到着色器实现
算法·图形学
AmyLin_200115 分钟前
【pdf2md-3:实现揭秘】福昕PDF SDK Python 开发实战:从逐字符提取到 LR 版面分析
开发语言·python·pdf·sdk·markdown·pdf2md
西西弟19 分钟前
最短路径之Floyd算法(数据结构)
数据结构·算法
IP老炮不瞎唠22 分钟前
Scrapy 高效采集:优化方案与指南
网络·爬虫·python·scrapy·安全
沪漂阿龙23 分钟前
深入浅出 Pandas apply():从入门到向量化思维
人工智能·python·pandas
我材不敲代码24 分钟前
OpenCV 实战——Python 实现图片人脸检测 + 视频人脸微笑检测
人工智能·python·opencv
小O的算法实验室25 分钟前
2026年SEVC,直觉模糊不确定环境下求解绿色多物品固定费用五维运输问题的多目标进化算法,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
海海不瞌睡(捏捏王子)36 分钟前
Unity A*寻路算法
算法·unity