[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
        
相关推荐
吴佳浩3 小时前
大模型量化部署终极指南:让700亿参数的AI跑进你的显卡
人工智能·python·gpu
Hcoco_me3 小时前
大模型面试题17:PCA算法详解及入门实操
算法
跨境卫士苏苏3 小时前
亚马逊AI广告革命:告别“猜心”,迎接“共创”时代
大数据·人工智能·算法·亚马逊·防关联
diegoXie4 小时前
Python / R 向量顺序分割与跨步分割
开发语言·python·r语言
七牛云行业应用4 小时前
解决OSError: No space left... 给DeepSeek Agent装上无限云硬盘
python·架构设计·七牛云·deepseek·agent开发
云雾J视界4 小时前
当算法试图解决一切:技术解决方案主义的诱惑与陷阱
算法·google·bert·transformer·attention·算法治理
Xの哲學4 小时前
Linux Miscdevice深度剖析:从原理到实战的完整指南
linux·服务器·算法·架构·边缘计算
BoBoZz194 小时前
CutWithScalars根据标量利用vtkContourFilter得到等值线
python·vtk·图形渲染·图形处理
失散134 小时前
Python——1 概述
开发语言·python
夏乌_Wx4 小时前
练题100天——DAY23:存在重复元素Ⅰ Ⅱ+两数之和
数据结构·算法·leetcode