[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
        
相关推荐
biter down1 天前
14:pytest-order 插件 顺序控制案例
开发语言·python·pytest
测试开发-学习笔记1 天前
从0开始搭建自动化(一)-appium+python
python·自动化
㳺三才人子1 天前
初探 Flask
后端·python·flask·html
AI算法沐枫1 天前
机器学习到底是什么?
人工智能·python·深度学习·机器学习·数据挖掘·大模型·#ai
小技与小术1 天前
玩转Flask
开发语言·python·flask
SilentSamsara1 天前
Python 性能优化:tracemalloc、profiling 与 C 扩展加速
开发语言·python·青少年编程·性能优化
冰小忆1 天前
大驼峰命名规范和小驼峰命名规范的区别是什么?
开发语言·python
高洁011 天前
知识图谱:AI的超级大脑
人工智能·python·数据挖掘·知识图谱
知识分享小能手1 天前
Flask入门学习教程,从入门到精通,Flask智能租房——前期准备 知识点详解(5)
python·学习·flask
Curvatureflight1 天前
【架构实战】生产级大模型 API 接入指南:流式响应(Streaming)异常处理与监控闭环
python·架构