[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
        
相关推荐
百锦再11 分钟前
低代码开发的约束性及ABP框架的实践解析
android·开发语言·python·低代码·django·virtualenv·rxjava
Actinen41 分钟前
【Python】——注释
python
自动化小秋葵1 小时前
Python入门经典题目
开发语言·python
居7然1 小时前
DeepSeek OCR:重新定义AI文档处理的“降本增效”新范式
人工智能·算法·语言模型·自然语言处理·大模型·ocr
while(1){yan}1 小时前
数据结构之堆
数据结构·python·算法
凌晨一点的秃头猪2 小时前
Python 常见 bug 总结和异常处理
开发语言·python·bug
mortimer2 小时前
用PySide6 构建一个响应式视频剪辑工具:多线程与信号机制实战
python·ffmpeg·pyqt
新子y2 小时前
【小白笔记】input() 和 print() 这两个函数
笔记·python
SleepyWhite0012 小时前
代码随想录Day61|Floyd 算法精讲、A * 算法精讲
算法·floyd算法·astar算法
Miraitowa_cheems2 小时前
LeetCode算法日记 - Day 84: 乘积为正数的最长子数组长度
数据结构·算法·leetcode·贪心算法·线性回归·深度优先·动态规划