[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
        
相关推荐
Data_agent16 小时前
Python 编程实战:函数与模块化编程及内置模块探索
开发语言·python
十铭忘16 小时前
windows系统python开源项目环境配置1
人工智能·python
lzllzz2317 小时前
bellman_ford算法
算法
Generalzy17 小时前
langchain deepagent框架
人工智能·python·langchain
栈与堆17 小时前
LeetCode 19 - 删除链表的倒数第N个节点
java·开发语言·数据结构·python·算法·leetcode·链表
sunfove17 小时前
麦克斯韦方程组 (Maxwell‘s Equations) 的完整推导
线性代数·算法·矩阵
Rui_Freely17 小时前
Vins-Fusion之 SFM准备篇(十二)
人工智能·算法·计算机视觉
万行17 小时前
机器学习&第二章线性回归
人工智能·python·机器学习·线性回归
nervermore99017 小时前
3.3 Python图形编程
python
zhengfei61117 小时前
世界各地免费电视频道的 M3U 播放列表。
python