[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
        
相关推荐
ʚ希希ɞ ྀ41 分钟前
岛屿数量 -- 图论
算法·深度优先·图论
Wang ruoxi2 小时前
Pygame 小游戏——贪吃蛇
python·pygame
aWty_2 小时前
实分析入门(11)--Cantor三分集
学习·数学·算法·实变函数
兰令水2 小时前
leecodecode【二叉树递归+对称】【2026.6.1打卡-java版本】
算法
大数据魔法师6 小时前
Streamlit(二十三)- 教程(二)- 动态导航
python·web
心中有国也有家9 小时前
GE图引擎深度解析——CANN的计算图优化与执行引擎
人工智能·pytorch·python·学习·numpy
地平线开发者10 小时前
profiler debug 工具用法与高一致性策略
算法·自动驾驶
卷毛的技术笔记10 小时前
告别硬编码!Spring AI Alibaba 实现 AI Agent 智能工具调用(Tool Calling)
java·人工智能·后端·python·spring·ai编程
编程大师哥10 小时前
匿名函数 lambda + 高阶函数
java·python·算法
vb20081110 小时前
FastAPI APIRouter
开发语言·python