[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
        
相关推荐
鹿角片ljp4 分钟前
LeetCode 141. 环形链表|从 HashSet 到快慢指针 O (1) 空间最优解
算法·leetcode·链表
you鬰5 分钟前
datawhale--llm-algo-leetcode9️⃣ SFT Training Loop
python·datawhale
薛定e的猫咪11 分钟前
(NeurIPS 2022)GraphGPS:MPNN 与全局注意力的融合之道
人工智能·深度学习·学习·算法
叫我:松哥12 分钟前
基于flask仿小米商城管理系统,使用flask开的一个商场网站
数据库·后端·python·flask
智购科技无人售货机工厂19 分钟前
2026自动售货机防拆机物理安全设计:从安全螺丝到结构互锁的工程实践~YH
android·网络·驱动开发·python·单片机·安全·云原生
2401_8685347826 分钟前
校园网规划与设计
python·pygame
小猴子爱上树31 分钟前
跨境电商AI批量图片翻译工具,视频字幕翻译免费试用
人工智能·python·音视频
zx_7414848141 分钟前
【Python入门】爬虫实战:Requests + XPath 从基础到实战
开发语言·爬虫·python
高洁0142 分钟前
Teacher Forcing技术解析
人工智能·python·深度学习·transformer·知识图谱
2601_962065251 小时前
从零创建一个 Django 项目
后端·python·django