[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
        
相关推荐
武帝为此1 分钟前
【专家系统介绍】
人工智能·算法
敲个大西瓜1 分钟前
flask ApI快速上手
python
@insist1231 分钟前
软件设计师-分治法核心原理与典型应用
算法·软考·软件设计师·软件水平考试
机器学习之心2 分钟前
PSO-SVR粒子群算法优化支持向量机回归+SHAP分析+新数据预测,MATLAB代码
算法·支持向量机·回归·pso-svr·灰狼算法优化支持向量机回归
浩瀚之水_csdn2 分钟前
【框架】flask路由深度解析
后端·python·flask
8Qi84 分钟前
环形链表刷题笔记(LeetCode热题100--141、142)
c语言·数据结构·c++·算法·leetcode·链表
Sagittarius_A*5 分钟前
图像去雾:从直方图增强到暗通道先验【计算机视觉】
图像处理·人工智能·python·opencv·计算机视觉·图像去雾·暗通道先验
zach01277 分钟前
神经符号系统驱动的宠物健康监测范式革命:基于安庆大观区多模态数据流的GEO精准引流拓扑重构
人工智能·python·重构·宠物
LEAKSENSE9 分钟前
漏液报警器白皮书:技术革新×应用实践·未来蓝图
大数据·人工智能·python
滴滴答滴答答10 分钟前
机考刷题之 13 LeetCode 1004 最大连续1的个数 III
java·算法·leetcode