[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
        
相关推荐
❁满城风絮*2 小时前
Claude Code 学习总结
python·agent·claude
维克兜率天4 小时前
【维克】复合型CTA:趋势+套利的双轮驱动
python·学习方法
伞伞悦读4 小时前
【第76期】两张3行表左连接变5行:主键、validate与未匹配排查完整教程
人工智能·python
用户8356290780515 小时前
使用 Python 在 Excel 中添加和自定义迷你图
后端·python
老师我太想进步了20265 小时前
【数据结构-4】算法美学之顺序表
数据结构·算法
用户8356290780515 小时前
使用 Python 在 Excel 图表中添加趋势线与回归方程
后端·python
风影同志783245 小时前
编码器是激活函数吗?—— 一个看起来很像、其实不是的类比
算法
特立独行的猫A5 小时前
一份 Markdown 发十个平台:cspub 一稿多投
java·后端·python
UIU1145 小时前
P1481 魔族密码
c++·算法·动态规划
深蓝AI6 小时前
HTTPX 超时 1 秒,接口为何还能跑 2.4 秒?
python