[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
        
相关推荐
lifewange15 小时前
pytest 找不到文件?直接在 pytest.ini 配置根目录 + 路径(最简单方案)
开发语言·python·pytest
城事漫游Molly15 小时前
研究设计核心 Toolkit:从“知道方法”到“真正会设计”
大数据·人工智能·算法·ai写作·论文笔记
yuanpan15 小时前
Python 桌面 GUI 入门开发:从 tkinter 窗口到简易记事本
开发语言·python
川石课堂软件测试15 小时前
软件测试|常见面试题整理
数据库·python·jmeter·mysql·appium·postman·prometheus
做个文艺程序员15 小时前
Multi-Agent 系统实战:用 Python + LangGraph 搭建多智能体协作工作流
python·多智能体·langgraph·multi-agent
bang冰冰16 小时前
Trae工具安装和使用教程(新手零基础入门,全程无坑)
java·人工智能·python
User_芊芊君子16 小时前
聊聊自由开发者常用的学习机会全解析
开发语言·人工智能·python
xh didida17 小时前
算法 -- 位运算
开发语言·c++·算法
weixin_3765932217 小时前
使用pyhon脚本方式将超链接保存到第一列以数字方式显示
python
byzh_rc17 小时前
[AI编程从入门到入土] 装饰器decorator
开发语言·python·ai编程