[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
        
相关推荐
D_FW6 分钟前
数据结构第二章:线性表
数据结构·算法
技术狂人16816 分钟前
(六)大模型算法与优化 15 题!量化 / 剪枝 / 幻觉缓解,面试说清性能提升逻辑(深度篇)
人工智能·深度学习·算法·面试·职场和发展
拾柒SHY18 分钟前
Python爬虫入门自学笔记
笔记·爬虫·python
Franciz小测测19 分钟前
如何实现 Web 触发后的“离线”升级?Systemd 异步机制与 A/B 状态机切换详解
python·部署·自动升级·离线升级
小北方城市网22 分钟前
第 9 课:Python 全栈项目性能优化实战|从「能用」到「好用」(企业级优化方案|零基础落地)
开发语言·数据库·人工智能·python·性能优化·数据库架构
E_ICEBLUE35 分钟前
PPT 智能提取与分析实战:把演示文档变成结构化数据
数据库·python·powerpoint
JSU_曾是此间年少36 分钟前
pytorch自动微分机制探寻
人工智能·pytorch·python
CoovallyAIHub39 分钟前
为你的 2026 年计算机视觉应用选择合适的边缘 AI 硬件
深度学习·算法·计算机视觉
汉克老师39 分钟前
GESP2025年12月认证C++六级真题与解析(单选题8-15)
c++·算法·二叉树·动态规划·哈夫曼编码·gesp6级·gesp六级
刘立军43 分钟前
程序员应该熟悉的概念(8)嵌入和语义检索
人工智能·算法