[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
        
相关推荐
爱昏羔5 小时前
下篇:从检索到交互 — 物流RAG问答系统与WebUI全实现
python·langchain·agent
_Jimmy_5 小时前
Agent引用数据库知识过时的增量同步方案
人工智能·python·langchain
min(a,b)6 小时前
学习第 4 天:面向对象与异常处理
python·学习·学习方法
拳里剑气8 小时前
C++算法:BFS解决FloodFill算法
c++·算法·bfs·宽度优先
yangshicong8 小时前
第19章:AI安全防护与AI安全
人工智能·python·安全·prompt·ai编程
果汁华8 小时前
Function Calling 与 Python 实战完整指南
开发语言·网络·python
c_lb72888 小时前
2026年不同基础做量化,先找AI能参与的位置
人工智能·python
wanderist.9 小时前
Lambda表达式在算法竞赛中的应用
java·开发语言·算法
稚南城才子,乌衣巷风流10 小时前
支配树(Dominator Tree)详解:概念、算法与应用
算法