[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
        
相关推荐
limenga10210 分钟前
支持向量机(SVM)深度解析:理解最大间隔原理
算法·机器学习·支持向量机
百***480728 分钟前
Python使用PyMySQL操作MySQL完整指南
数据库·python·mysql
coder江31 分钟前
二分查找刷题总结
算法
PNP Robotics1 小时前
PNP机器人上海宝山智能机器人年会发表机器人10年主题演讲演讲
人工智能·python·机器人
___波子 Pro Max.1 小时前
Python获取当前脚本目录路径
python
努力成为大牛吧1 小时前
Pycharm 接入 Deepseek API完整版教程
ide·python·pycharm
闲人编程1 小时前
Python对象模型:一切都是对象的设计哲学
开发语言·python·模型·对象·codecapsule·下划线
二川bro1 小时前
Python大语言模型调优:LLM微调完整实践指南
开发语言·python·语言模型
wa的一声哭了1 小时前
Webase部署Webase-Web在合约IDE页面一直转圈
linux·运维·服务器·前端·python·区块链·ssh
坚持就完事了2 小时前
蓝桥杯中Python常用的库与模块
python·算法