[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
        
相关推荐
南极星10057 分钟前
2026电赛E题有感
python·opencv·电赛
看浪的路人9 分钟前
第3讲:代码补全引擎
开发语言·windows·python
tudousisi22217 分钟前
P4447 [AHOI2018初中组] 分组 题解复盘
算法
SNAKEpc1213818 分钟前
OpenGL(十一)- 变换管线
c语言·c++·算法·矩阵·图形渲染
想会飞的蒲公英30 分钟前
PyTorch 学习率实战:从零理解衰减策略与调度器
人工智能·pytorch·python·深度学习·机器学习
布值倒区什么name43 分钟前
python文件IO学习
python
丁引1 小时前
《数据清洗的艺术:如何用20行核心逻辑优雅地删除无标签图片》
前端·数据库·python
梦想的旅途21 小时前
企业微信API二次开发:外部群模块功能清单与全场景对接
java·python·企业微信
0566461 小时前
Python高级——迭代器
开发语言·python·学习
老白干2 小时前
基于 Spring AOP 的操作日志记录:以 DeptController 增删接口为例
java·python·spring