[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
        
相关推荐
H愚公移山H4 分钟前
Tengine2.4.1 + OpenSSL1.1.1w 全平台编译踩坑手册(CentOS7 x86_64|Linux x64|ARM64|2026实战复盘)
python
码云骑士15 分钟前
120-视频理解-大模型视频分析-抽帧-自动字幕摘要-高光片段
python·音视频
猎头南楼19 分钟前
杭州算法工程师,偏大模型应用落地
算法
xfan_me21 分钟前
手机在网状态接口-空号查询-空号过滤API
数据库·人工智能·python·智能手机
测试秃头怪24 分钟前
Postman中变量的使用
自动化测试·软件测试·python·测试工具·测试用例·接口测试·postman
间歇性努力持续性发呆的野生快乐选手25 分钟前
二分模板(整型,浮点型)
数据结构·c++·算法
ynchyong25 分钟前
词云(Word Cloud) 使用方法
python·统计·词云
evans在进步29 分钟前
LeetCode 189 轮转数组:三次反转为什么能实现右旋?
数据结构·算法·leetcode
豆沙沙包?32 分钟前
函数重载/类和对象(P14-P60)
前端·算法
Alkaid207735 分钟前
我把文件和脚本放一起了,Python 就是看不见?新手必看的绝对路径 vs 相对路径终极避坑指南
python·ai编程