[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
        
相关推荐
rsuhbsrjms11 分钟前
可视采耳仪器多少钱一台?可视耳勺哪个牌子好?口碑好的可视耳勺
网络·人工智能·算法
finhaz13 分钟前
神经网络等机器学习模型的看法
算法
z2005093014 分钟前
【linux学习】深入理解 Linux 下的静态库与动态库
开发语言·c++·算法
2601_9611940214 分钟前
考研政治历年真题库
python·考研·django·virtualenv·pygame·tornado
兰令水15 分钟前
【helloagent】第四章 agent范式总结+面经
python·语言模型
妄想出头的工业炼药师17 分钟前
腿式里程计
人工智能·算法·开源
SoftLipaRZC18 分钟前
C语言自定义类型:联合和枚举完全指南
c语言·算法
AI视觉网奇20 分钟前
3d查看 预览软件
python
练习时长一年2 小时前
LeetCode热题100(二叉树的最大路径和)
算法·leetcode·职场和发展
不知名的老吴2 小时前
Lambda表达式与新的Streams API相结合
开发语言·python