[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
        
相关推荐
想唱rap7 小时前
应用层协议与序列化
linux·运维·服务器·网络·数据结构·c++·算法
alwaysrun7 小时前
Python自动提取邮件订阅链接并解析
python·url·邮件·ai提取
何中应7 小时前
Conda安装&使用
python·conda·python3.11
重生之我是Java开发战士7 小时前
【笔试强训】Week3:重排字符串,分组,DNA序列
算法
We་ct7 小时前
LeetCode 97. 交错字符串:动态规划详解
前端·算法·leetcode·typescript·动态规划
热心网友俣先生8 小时前
2026年第二十三届五一数学建模竞赛B题四问参考答案+多算法对比
算法·数学建模
无敌昊哥战神8 小时前
【LeetCode 37】解数独 (Sudoku Solver) —— 回溯法详解 (Python/C/C++)
c语言·c++·python·算法·leetcode
风流 少年8 小时前
Python Web框架:FastAPI
前端·python·fastapi
风筝在晴天搁浅8 小时前
LeetCode 162.寻找峰值
算法·leetcode
Qres8218 小时前
Rabrg/artificial-life test
python·模拟