[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 分钟前
高斯滤波实现算法
c++·算法·最小二乘法
张张123y19 分钟前
RAG从0到1学习:技术架构、项目实践与面试指南
人工智能·python·学习·面试·架构·langchain·transformer
Shi_haoliu27 分钟前
openClaw源码部署-linux
前端·python·ai·openclaw
gf132111129 分钟前
python_查询并删除飞书多维表格中的记录
java·python·飞书
一叶落4381 小时前
题目:15. 三数之和
c语言·数据结构·算法·leetcode
带娃的IT创业者1 小时前
WeClaw 离线消息队列实战:异步任务队列如何保证在服务器宕机时不丢失任何一条 AI 回复?
运维·服务器·人工智能·python·websocket·fastapi·实时通信
老鱼说AI2 小时前
CUDA架构与高性能程序设计:异构数据并行计算
开发语言·c++·人工智能·算法·架构·cuda
罗湖老棍子2 小时前
【例 1】数列操作(信息学奥赛一本通- P1535)
数据结构·算法·树状数组·单点修改 区间查询
big_rabbit05022 小时前
[算法][力扣222]完全二叉树的节点个数
数据结构·算法·leetcode