[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
        
相关推荐
lzqrzpt6 分钟前
临沂LED驱动电源制造工艺解析与工程选型避坑指南
python·制造
ai小陈7 分钟前
Python 3.12与CUDA 12.8镜像实战:启动GPU实例后的五项自检
开发语言·人工智能·python·深度学习·ai·gpu算力
Thomas.Sir11 分钟前
第48课:TensorFlow|TF模型线上部署入门【本地服务封装、接口快速开发】
人工智能·python·tensorflow
Bruce_Liuxiaowei14 分钟前
录屏片段无损合并:从 ffmpeg concat 原理到 Python 自动化脚本
python·ffmpeg·自动化
沉淀的.晴天19 分钟前
FreeRTOS信号量
数据结构·算法
renzao_ai39 分钟前
本地 35B 大模型部署实战:Ollama 跑 Ornith-35B 全流程
python·llama·免费ai大模型
the局外人1 小时前
学习 FastAPI 的 Day 4:完成用户系统与接口联调(完结)
后端·python·fastapi
青山木1 小时前
Hot 100 --- 打家劫舍
java·数据结构·算法·leetcode·动态规划
机器学习之心1 小时前
均值、中值、圆周期:三种 InSAR 干涉相位滤波的实测对比与参数取舍
算法·均值算法