[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
        
相关推荐
PILIPALAPENG1 分钟前
第3周 Day 2:Function Calling —— 让 Agent 听懂人话,自己干活
前端·人工智能·python
高木木的博客26 分钟前
数字架构智能化测试平台(1)--总纲
人工智能·python·nginx·架构
zhangchaoxies31 分钟前
golang如何使用SQLx原生SQL查询_golang SQLx原生SQL查询使用方法
jvm·数据库·python
m0_7436239231 分钟前
mysql如何优化InnoDB缓冲池大小_mysql缓冲池内存调优
jvm·数据库·python
m0_6178814235 分钟前
如何操作 XML 数据_XMLTYPE 与 EXTRACT 函数解析节点
jvm·数据库·python
qq_3345635539 分钟前
golang如何实现SSTable持久化_golang SSTable持久化实现要点
jvm·数据库·python
2301_7775993741 分钟前
Redis怎样应对大规模集群的重启风暴_分批次重启节点并等待集群状态恢复绿灯后再继续操作
jvm·数据库·python
qq_452396231 小时前
【工程实战】第十篇:性能监控集成 —— 自动化脚本的“副产品”:不仅仅是功能测试
python·功能测试·自动化
来自远方的老作者1 小时前
第10章 面向对象-10.4 继承
开发语言·python·继承·单继承·多继承·super函数
逻辑驱动的ken1 小时前
Java高频面试考点场景题09
java·开发语言·数据库·算法·oracle·哈希算法·散列表