[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
        
相关推荐
九河_2 分钟前
从requirements.txt中安装缺失的包
python·conda·pip·环境管理
llm大模型算法工程师weng2 分钟前
Python爬虫实现指南:从入门到实战
开发语言·爬虫·python
Allen_LVyingbo5 分钟前
《狄拉克符号法50讲》习题与解析(下)
算法·决策树·机器学习·健康医疗·量子计算
豆沙糕5 分钟前
大模型面试高频题:请详细讲解检索中的BM25算法
人工智能·算法
不才小强6 分钟前
查找算法详解:二分查找
数据结构·算法
君义_noip9 分钟前
信息学奥赛一本通 4164:【GESP2512七级】学习小组 | 洛谷 P14922 [GESP202512 七级] 学习小组
学习·算法·动态规划·gesp·信息学奥赛
MicroTech202510 分钟前
微算法科技(NASDAQ :MLGO)面向区块链的系统的高效反量子晶格盲签名技术
科技·算法·区块链
AI效率工坊10 分钟前
【Python实战】10万行数据自动清洗:pandas+AI智能识别+异常检测完整方案
人工智能·python·pandas
乔江seven16 分钟前
LlamaIndex 实现ReAct Agent
前端·python·react.js
lifallen22 分钟前
一篇文章讲透 Flink State
大数据·数据库·python·flink