[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
        
相关推荐
HZZD_HZZD17 小时前
智能电表选CoAP还是MQTT?合众致达万表实测:CoAP省流17.3%、续航提升38%,附报文拆解与选型矩阵
算法
m0_5191964017 小时前
【设计模式】java的习题
开发语言·python
linux-hzh18 小时前
百日算法修炼 · Day 05
java·算法
paopaokaka_luck18 小时前
基于springboot3+vue3的云南本土影视文旅推荐平台(协同过滤算法、Echarts图形化分析)
前端·spring boot·学习·算法·echarts·mybatis
pt104318 小时前
网络自动化Python课程:Git版本控制基础入门与实验演示
网络·python·自动化
circuitsosk18 小时前
不止于API调用:大模型推理加速与云原生服务化部署指南
python·云原生·agent·vllm·推理加速·大模型部署·ensorrt-llm
萌动的小火苗18 小时前
深度神经网络中,梯度消失和梯度爆炸的根本原因是什么?有哪些解决方法?【文末含面试万能总结】
人工智能·python·深度学习·神经网络·dnn
卷无止境18 小时前
当Python遇上并发:concurrent.futures的核心逻辑与实战技巧
后端·python
Ivanqhz18 小时前
泰勒展开(Taylor Expansion)
算法·决策树·机器学习·集成学习
卷无止境18 小时前
编程语言里到底有没有经济学规律?
后端·python