[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
        
相关推荐
性野喜悲1 小时前
python将excel中的链接转成图片并替换链接展示在excel中【将pdf的第一页插入excel并将对应信息获取到插入签名等位置】
开发语言·python·excel
Marvel__Dead1 小时前
基于 AI 大模型的百度旋转验证识别(通用能力极强)
人工智能·爬虫·python·验证码识别·ai 大模型
code bean1 小时前
【LangChain 】 自定义解析器实战指南:从原理到 10 个业务场景落地
算法·langchain
Leinwin1 小时前
OpenAI Daybreak实战指南:如何将AI安全检查嵌入你的开发流程
后端·python·flask
monkeyhlj1 小时前
LangChain - V1.0
python·langchain·ai编程
zh路西法1 小时前
【Qwen2.5本地部署】超简单pytorch-gpu部署教程
人工智能·pytorch·python
念恒123061 小时前
基础IO(一切皆文件)
linux·c语言·c++·算法
狐狐生风2 小时前
LangGraph Human-in-the-loop 全解
python·langchain·prompt·langgraph·agentai
d111111111d2 小时前
MQTT+STM32+云平台+AT命令的编写
服务器·笔记·stm32·单片机·嵌入式硬件·算法
倒霉熊dd2 小时前
Python 学习(第二部分:函数、模块与面向对象编程)
前端·数据库·python