[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
        
相关推荐
饮水桶_T33 分钟前
Git笔记
开发语言·笔记·算法
指掀涛澜天下惊1 小时前
强化学习进阶篇十四 DPO算法
深度学习·算法·机器学习·sft·预训练·dpo
龙腾AI白云1 小时前
多源数据融合:把零散信号拼成一致图景
大数据·人工智能·python·机器学习·知识图谱
艾派森2 小时前
深度学习实战-基于VGG19的健康和白化珊瑚图像分类识别模型
人工智能·python·深度学习·分类
鲸渔2 小时前
【AI Agent系列课程26-Python 基础26】复盘:Python 接口开发知识清单
开发语言·python·ai编程
2401_868534782 小时前
55 个热门网络面试问题及答案
网络·python
aifannihao2 小时前
ON CONFLICT 冲突后返回空:sqlite3 实测 get-or-create
数据库·python·postgresql·sqlite3·标准库
用户0332126663673 小时前
使用 Python 合并 Excel 工作簿
python
__underline__3 小时前
冷门Python知识点008篇:__int__、__index__与__float__,Python数值转换的真实回退顺序?
后端·python
AAA修煤气灶刘哥3 小时前
我都切到下一张图了,Agent 怎么还在解释上一张?
人工智能·算法·架构