[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
        
相关推荐
普通网友9 分钟前
共识算法实现:从工作量证明到权益证明的演进
算法·区块链·共识算法
zhiSiBuYu051726 分钟前
Python3 模块开发与应用实战指南
python
ldmd2841 小时前
地图生成算法(噪声篇-Perlin,Simplex,Value noise)
算法·go·地图生成
databook1 小时前
用方差阈值过滤掉“惰性特征”
python·机器学习·scikit-learn
Freak嵌入式1 小时前
MCU 低功耗模式解析:时钟门控、电源门控、深度休眠
人工智能·python·单片机·嵌入式硬件·开源·依赖倒置原则·micropython
国科安芯2 小时前
FreeRTOS RISC-V 浮点上下文切换移植:在 IAR 工程中完整保存 FPU 寄存器
java·开发语言·单片机·嵌入式硬件·算法·系统架构·risc-v
小陈phd2 小时前
集成检索介绍
算法
小poop2 小时前
轮转数组:从暴力到最优,一题掌握算法复杂度分析
数据结构·算法·leetcode
樱桃读报僵尸2 小时前
说说 LLMRouter,Agent 执行过程中怎么动态的选择 LLM
算法
weixin_BYSJ19872 小时前
springboot校园自习室管理小程序---附源码32142
java·javascript·spring boot·python·django·flask·php