[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
        
相关推荐
流云鹤9 小时前
1. 配置环境、创建导航栏
python·django
三亚兴嘉装饰9 小时前
准备在三亚装房子找哪家装修
python
Keven_119 小时前
算法札记:如何卡SPFA
算法·spfa
可编程芯片开发10 小时前
基于电压电流双闭环控制的三相整流器系统simulink建模与仿真
算法
可编程芯片开发10 小时前
基于ADRC自抗扰算法的UAV飞行姿态控制系统simulink建模与仿真
算法
Mx_coder10 小时前
8年Java开发者AI转型第二周:RAG系统深入 + 向量数据库实战(Day 8-10)
python
学究天人10 小时前
数学公理体系大全:第七章 连续统假设与力迫法简介
人工智能·算法·机器学习·数学建模·动态规划·图论·抽象代数
Keven_1110 小时前
算法札记:SPFA什么时候用队列什么时候用栈
算法·spfa
ximen502_10 小时前
Python 语言知识总结
开发语言·python
:-)10 小时前
基础算法-选择排序
数据结构·算法·排序算法