[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
        
相关推荐
hahaha60169 分钟前
HLS高层次综合设计--axi之burst纠偏
开发语言·算法·fpga开发·c#
天空属于哈夫克312 分钟前
企业微信 API 自动发送消息:从流程到实战
python·自动化·企业微信
hans汉斯14 分钟前
【计算机科学与应用】基于联合熵驱动改进麻雀搜索优化VMD的DAS信号去噪方法
深度学习·算法·yolo·软件工程·汉斯出版社
SunnyDays101116 分钟前
如何使用 Python 给 PDF 添加附件:文档附件与附件注释
开发语言·python·pdf
步行cgn16 分钟前
@Value 详解:Spring 属性注入的核心注解
java·python·spring
词却17 分钟前
机器学习入门:手写数字识别与算法对比
人工智能·算法·机器学习
SamChan9018 分钟前
PDF翻译服务端到端基准测试:4款主流方案的吞吐量、延迟、内存占用对比
服务器·网络·python·ai·pdf·wpf
张欣-男44 分钟前
3分钟理解线性代数
线性代数·算法
白狐_7981 小时前
408 数据结构|外部排序优化:怎么减少时间开销
数据结构·算法
小白说大模型1 小时前
Hermes 全配置指南:从裸版到 AI Agent 天花板
大数据·人工智能·学习·算法·机器学习·数据挖掘