[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
        
相关推荐
飞Link8 小时前
什么是 AirSim?一文读懂无人机仿真平台
python·算法·无人机
曲径海盗8 小时前
【Python 学习第 38 天】for 循环
python·学习笔记·编程入门
在世修行9 小时前
智学文枢:变式题生成引擎
python·ai·pyside·题目生成
一去不复返的通信er10 小时前
贪心算法-合并区间(LeetCode 56)
算法·leetcode·贪心算法
On The Road :10 小时前
Java 多线程详解:从入门到线程安全
java·python·安全
岁月宁静11 小时前
如何设计支持 Skills 的 Agent?一套可扩展的四层架构
python·agent
Shaoshing11 小时前
LeetCode100 49. 字母异位词分组
java·算法
岁月宁静11 小时前
CrewAI 快速上手:10 分钟搭建你的第一个 Agent 团队
python·agent
YFJ_mily11 小时前
第二届区块链技术与基础模型国际学术会议(BTFM2027)
算法·区块链·能源·智能系统·rdlink研发家·机器人自动化