[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
        
相关推荐
烛阴7 分钟前
Python数据可视化:从零开始教你绘制精美雷达图
前端·python
276695829213 分钟前
朴朴超市小程序分析
java·python·小程序·node·sign·朴朴超市·sign-v2
李小白杂货铺16 分钟前
识别和破除信息茧房
算法·信息茧房·识别信息茧房·破除信息茧房·算法推荐型茧房·观点过滤型茧房·茧房
重生之我要当编程大佬44 分钟前
关于打不开pycharm的解决方法(一)
ide·python·pycharm
深圳佛手1 小时前
AI 编程工具Claude Code 介绍
人工智能·python·机器学习·langchain
来荔枝一大筐1 小时前
C++ LeetCode 力扣刷题 541. 反转字符串 II
c++·算法·leetcode
apocelipes1 小时前
POSIX兼容系统上read和write系统调用的行为总结
linux·c语言·c++·python·golang·linux编程
暴风鱼划水1 小时前
算法题(Python)数组篇 | 6.区间和
python·算法·数组·区间和
Derrick__12 小时前
Web Js逆向——加密参数定位方法(Hook)
python·js