[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
        
相关推荐
Dust-Chasing7 分钟前
Claude Code源码剖析 - Claude Code 上下文压缩机制
人工智能·python·ai
小欣加油16 分钟前
leetcode1926 迷宫中离入口最近的出口
数据结构·c++·算法·leetcode·职场和发展
Cloud_Shy6181 小时前
解读《Effective Python 3rd Edition》:从练气到老魔(第五章 Item 33 - 35)
开发语言·人工智能·笔记·python·学习方法
abcy0712132 小时前
python pandas csv异步后台清洗前端优先返回成功信息
前端·python·pandas
颜酱2 小时前
LangChain使用RAG 入门:让大模型读懂你的私有文档
python·langchain
天天进步20153 小时前
Python全栈项目--校园智能宿舍管理系统
开发语言·python
happymaker06263 小时前
LeetCodeHot100——42.接雨水
算法
测试员周周3 小时前
【AI测试智能体-面试】AI测试面试60题(附回答思路)
人工智能·python·功能测试·测试工具·单元测试·自动化·测试用例
用户8356290780513 小时前
使用 Python 操作 Word 评论和回复
后端·python
阿正的梦工坊3 小时前
【Rust】07-错误处理:Option、Result 与 ? 运算符
开发语言·算法·rust