[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
        
相关推荐
lisw059 分钟前
微分与积分的本质区别解析
算法·数学建模·极限编程
隐擎fox19 分钟前
深入 Android 移动端风控与协议层对抗:内核级虚拟环境检测、网络堆栈特征伪装与住宅 IP 协同实战
android·网络·python·网络协议·tcp/ip
“AI国潮设计-小江”24 分钟前
【AIGC实战】Python+SDXL批量生成「潮汕英歌舞冰淇淋蛋糕&红桃粿咖啡」IP,固定角色形象批量出甜品商业效果图
开发语言·人工智能·python·prompt·aigc
xys_6781 小时前
深挖数据结构:树和二叉树(上)
数据结构·算法
Merrill_hh1 小时前
Python环境搭建
python
用户019027581611 小时前
如何用 Python 回测布林带突破策略?
python
Interview Aid1121 小时前
Google SWE Intern VO 面经:两轮 Coding,Follow-up 考察 BFS 状态
算法
4SAPI1 小时前
企业Agent落地选型:大模型API接入方案迁移实践与稳定性评估
人工智能·python·php
用户019027581611 小时前
如何用 Python 计算 CR 能量指标(中间意愿指标)?
python
曲径海盗1 小时前
【Python 学习第 34 天】条件判断 if/else
python·学习笔记·编程入门