[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
        
相关推荐
Yao.Li7 分钟前
Dify 本地环境忘记登录密码问题排障文档
人工智能·python
_MyFavorite_13 分钟前
JAVA重点基础、进阶知识及易错点总结(14)字节流 & 字符流
java·开发语言·python
Eric.Lee202115 分钟前
python实现pdf转图片png
linux·python·pdf
deep_drink22 分钟前
1.2、Python 与编程基础:文件处理与常用库
开发语言·python·elasticsearch·llm
Hello.Reader23 分钟前
一堆 `.ts` 分片合并后音画不同步?从问题定位到通用修复脚本的完整实战
python·ffmpeg·视频
BieberChen33 分钟前
匈牙利匹配算法 (Hungarian Algorithm) 详解
算法
春栀怡铃声41 分钟前
常考排序的梳理
数据结构·算法·排序算法
第二只羽毛42 分钟前
第六章 图
大数据·数据结构·算法·深度优先·图论·广度优先·宽度优先
好家伙VCC44 分钟前
**CQRS模式实战:用Go语言构建高并发读写分离架构**在现代分布式系统中,随着业务复杂度的提升和用户量的增长,传统的单数据库模型逐
java·数据库·python·架构·golang
fy1216344 分钟前
Java进阶——IO 流
java·开发语言·python