[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
        
相关推荐
君义_noip10 分钟前
洛谷 P4777 【模板】扩展中国剩余定理(EXCRT)
算法·数论·信息学奥赛·csp-s
天赐学c语言10 分钟前
12.14 - 搜索旋转排序数组 && 判断两个结构体是否相等
数据结构·c++·算法·leecode
咖啡の猫16 分钟前
Python字典的查询操作
数据库·python·c#
1024肥宅25 分钟前
JavaScript 性能与优化:数据结构和算法
前端·数据结构·算法
kaikaile199538 分钟前
MATLAB 灰度图像的二维傅里叶变换
算法·计算机视觉·matlab
仰泳的熊猫1 小时前
1112 Stucked Keyboard
数据结构·c++·算法·pat考试
smile_Iris1 小时前
Day 38 GPU训练及类的call方法
开发语言·python
roman_日积跬步-终至千里1 小时前
【计算机算法与设计(14)】例题五:最小生成树:Prim算法详细解释:π的含义、更新逻辑和选点原因
算法
让学习成为一种生活方式1 小时前
压缩文件夹下下所有文件成压缩包tar.gz--随笔016
算法
嗷嗷哦润橘_1 小时前
AI Agent学习:MetaGPT项目之RAG
人工智能·python·学习·算法·deepseek