[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
        
相关推荐
追随者永远是胜利者4 分钟前
(LeetCode-Hot100)215. 数组中的第K个最大元素
java·算法·leetcode·职场和发展·go
We་ct8 分钟前
LeetCode 112. 路径总和:两种解法详解
前端·算法·leetcode·typescript
敲代码的哈吉蜂9 分钟前
haproxy的算法——静态算法
linux·运维·服务器·算法
艾醒11 分钟前
打破信息差——2月21日AI全域热点全复盘
后端·算法
tankeven13 分钟前
自创小算法00:数据分组
c++·算法
样例过了就是过了21 分钟前
LeetCode热题100 矩阵置零
算法·leetcode·矩阵
一行代码改三天23 分钟前
奖学金+回文数2+加法器
算法
33三 三like23 分钟前
高精度计算
开发语言·c++·算法
sg_knight31 分钟前
对象池模式(Object Pool)
python·设计模式·object pool·对象池模式