[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
        
相关推荐
linux-hzh13 小时前
百日算法修炼 · Day 09
数据结构·算法·排序算法
DFT计算杂谈13 小时前
Janus单层Cr2SSe中的应变可调多压电效应与谷电子学
人工智能·算法·机器学习
今天AI了吗13 小时前
从 LLM 到 Agent Skill:把 AI 底层概念串起来
数据库·人工智能·sql·深度学习·神经网络·算法·机器学习
刘新洲13 小时前
别再只做会聊天的 Agent:我用 1 天把工具调用做成了可验证、可评测的工程系统
人工智能·python·openai
码云骑士13 小时前
102-向量数据增删改查-增量更新-过期策略-向量漂移重索引
python
Molecular_Chat13 小时前
Biotin SNA 生物素偶联凝集素结合特异性、生物素标记效率定量表征研究
javascript·python
WILLF13 小时前
Python vs JavaScript 异常处理对比
前端·python
hanlin0314 小时前
动态规划专练:力扣第1035、392题
算法·leetcode·动态规划
问天_观心14 小时前
python之uv库的学习
开发语言·python
vx-程序开发14 小时前
django汽车租赁系统---附源码25360
java·javascript·spring boot·python·eclipse·django·php