[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
        
相关推荐
学究天人15 小时前
数学公理体系大全:Comprehensive Collection of Mathematical Axiom Systems(补充卷9)
人工智能·线性代数·算法·数学建模·动态规划·原型模式·抽象代数
Keven_1115 小时前
算法札记:图的存储方式
算法·图论
斯文的八宝粥15 小时前
SERL:让真机强化学习从“难用”走向“可复现”的强化学习框架 ----(4)算法篇(DrQ vs VICE)
算法
埃博拉酱15 小时前
Pip/Conda 混用导致的 CRT 版本冲突问题:[WinError 1114] 动态链接库(DLL)初始化例程失败
windows·python
刘小八15 小时前
LangGraph 人机交互实战:Interrupt、人工审批与工作流恢复
人工智能·python·人机交互
yangdaxiageo15 小时前
算法时代的“心智置顶“:《功夫女足》如何构建GEO正向飞轮
人工智能·科技·算法·aigc
YMWM_15 小时前
python-venv虚拟环境
linux·开发语言·python
ysa05103015 小时前
【板子】欧拉序
c++·笔记·算法·深度优先·图论
大耳朵糊涂16 小时前
链表的基础操作(二)
算法
Tbisnic16 小时前
23.大模型开发:深度学习----CNN 卷积神经网络 与 RNN 循环神经网络
人工智能·python·rnn·深度学习·cnn·ai大模型