[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
        
相关推荐
金融小师妹3 小时前
多因子智能推演:油价回落6%与黄金震荡上行的关联解析——AI预测框架
大数据·python·深度学习
坚持编程的菜鸟5 小时前
模拟实现memmove
c语言·算法·模拟实现memmove
BUG研究员_6 小时前
Runnable与LCEL
开发语言·人工智能·python
老马聊技术6 小时前
Pytorch深度学习环境配置与测试
人工智能·pytorch·python
Python私教7 小时前
AI Agent 上生产要不要开写权限?我把执行链拆成 4 道闸门
人工智能·后端·python
天才测试猿7 小时前
软件测试知识总结(基础篇)
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例
wabs6667 小时前
关于图论【最短路径之Dijkstra算法(堆优化版)|卡码网47.参加科学大会的思考】
数据结构·算法·图论·优先级队列·邻接表·小顶堆·卡码网
崔子末7 小时前
某影视库剧集列表以及查询接口逆向
爬虫·python
gogogo出发喽7 小时前
v3 admin
python