[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
        
相关推荐
大草原的小灰灰几秒前
Python面向对象编程
开发语言·python
华研前沿标杆游学8 分钟前
企业参访入口 | 走进华为坂田基地,深圳华为坂田基地考察游学参访
python
垆边人似月.15 分钟前
日志时间窗口内的最大并发请求数(100分 / 滑动窗口 + 排序)
数据结构·c++·算法
Nil20822 分钟前
leetcode 70爬楼梯
算法·leetcode·动态规划
垆边人似月.34 分钟前
最长递增子序列的个数(200分 / 动态规划)
算法·动态规划
朝朝辞暮i1 小时前
VLA 系统学习第 12 课:为什么机器人不能只看一帧?——时间序列、Observation History 与 Action Chunk
人工智能·python·深度学习·神经网络·vla
朝朝辞暮i1 小时前
VLA 系统学习第 8 课:Optimizer 到底在干什么?——从 Learning Rate 到 SGD、Momentum 和 Adam
人工智能·python·深度学习·神经网络·vla
镜子AI1 小时前
教培机构多模态内容跨模态检索系统:基于CLIP的统一表征与图文混合召回算法
人工智能·python·算法·机器学习
落魄大学生之流水线上谋生计1 小时前
Selenium 入门到实战:用 Python 写出稳定的浏览器自动化
python·selenium·自动化
汤米粥1 小时前
后端开发主流技术方案
java·python·golang·php·nodejs·后端开发