[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
        
相关推荐
Doubbbbbbble云12 小时前
多维空间索引结构R树与KD树性能对比研究4
算法
海上小飞龙12 小时前
【KMP算法-中篇】next 数组的递推:往前填一位,靠的是往回退几步
算法
lusklusklusk12 小时前
Python 四大数据结构详解:元组、列表、集合、字典的特点与增删改查
数据结构·windows·python
打工仔折腾 AI12 小时前
把模型切换交给平台:用蓝耘智能路由搭建商品评论分析工具
java·服务器·前端·后端·python·性能优化·ai agent 实战
keyipatience12 小时前
B树详解:从零构建平衡多路搜索树
数据结构·b树·算法·图搜索
ynchyong12 小时前
python list 地常用操作
开发语言·python
梦在远山后12 小时前
PostgreSQL 锁与死锁:结合 DevMind 讲清楚
python·postgresql·agent
郝学胜_神的一滴13 小时前
AI 编程智能体 01:普通程序员的下一个逆天改命风口
人工智能·python
FluxArt13 小时前
GPT Image 2.5 多图参考怎么用:Flux Art 生成与编辑教程
数据结构·gpt·算法
zh路西法13 小时前
【ResNet18】从图像到视觉特征:卷积神经网络如何理解图像
pytorch·python·神经网络·cnn·resnet·resnet18