[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
        
相关推荐
92year4 分钟前
我用运筹学穷举了麦当劳全菜单:30 块预算,怎么吃到全局最优?
python·agent·mcp
用户7624117567055 分钟前
第三章 流程控制语句
python
wang09079 分钟前
硬着头皮学数据结构和算法之Myers算法
数据结构·算法
东莞市云毅网络有限公司18 分钟前
结构化标注缺失怎么查:JSON-LD抽取与每日巡检脚本实现
python·sqlite·自动化运维·geo·数据监测
蓝悦无人机20 分钟前
无人机系列之飞控算法:从PID到AI,飞行控制的核心进化
人工智能·算法·无人机·飞控系统
憨波个22 分钟前
【说话人日志】DiariZen
人工智能·深度学习·算法·语音识别
用户73416810354824 分钟前
被忽视的输入:为什么变工况故障诊断需要引入控制回路信号?
算法
2601_9629666432 分钟前
数学与应用数学专业准备风险管理岗,2027届秋招金融知识和工具技能怎么补?
python·sql
垆边人似月.36 分钟前
华为机试题 :最长递增子序列题目
数据结构·c++·算法·华为
码流子39 分钟前
02-易迁信创兼容引擎
大数据·数据库·python