[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
        
相关推荐
xyz_CDragon1 分钟前
OpenClaw Skills 完全指南:ClawHub 安装、安全避坑与自定义开发(2026)
人工智能·python·ai·skill·openclaw·clawhub
断眉的派大星2 分钟前
pytorch中view和reshape的区别
人工智能·pytorch·python
wsoz5 分钟前
Leetcode普通数组-day5、6
c++·算法·leetcode·数组
y = xⁿ5 分钟前
【LeetCode】双指针:同向快慢针
算法·leetcode
啊哦呃咦唔鱼6 分钟前
LeetCode hot100-105从前序与中序遍历序列构造二叉树
算法
favour_you___7 分钟前
2026_4_8算法练习题
数据结构·c++·算法
程序员阿明8 分钟前
spring boot3 集成jjwt(java-jwt)版本的
java·spring boot·python
Fleshy数模10 分钟前
基于MediaPipe实现人体姿态与脸部关键点检测
python·opencv·计算机视觉
汀、人工智能16 分钟前
[特殊字符] 第57课:搜索旋转排序数组
数据结构·算法·数据库架构·图论·bfs·搜索旋转排序数组
星马梦缘16 分钟前
jupyter Kernel Disconnected崩溃的修复
ide·python·jupyter