[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
        
相关推荐
Tisfy2 分钟前
LeetCode 3713.最长的平衡子串 I:计数(模拟)
算法·leetcode·题解·模拟
月疯2 分钟前
陀螺仪和加速度计(模拟状态,计算运动状态)
算法
cuber膜拜4 分钟前
Tenacity 原理与基本使用
服务器·网络·python·装饰器模式·tenacity
Myosotis5134 分钟前
作业 第三次
开发语言·python
cuber膜拜6 分钟前
PyBreaker 原理与基本使用
服务器·网络·python·pybreaker
Σίσυφος19007 分钟前
双目立体视觉 数学推导(从 F → E → R,T)
算法
学Linux的语莫8 分钟前
模型转为RKNN格式
python·深度学习·机器学习
Albert Edison14 分钟前
【Python】文件
android·服务器·python
沉睡的无敌雄狮16 分钟前
可编程数字人落地实践:某省广电用矩阵跃动API重构工作流(选题→政策图谱→方言音色→审稿水印),附Python调度代码
人工智能·python·重构·排序算法·kmeans
Hcoco_me16 分钟前
目标追踪概述、分类
人工智能·深度学习·算法·机器学习·分类·数据挖掘·自动驾驶