[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
        
相关推荐
DuHz5 小时前
论文精读:大语言模型 (Large Language Models, LLM) —— 一项调查
论文阅读·人工智能·深度学习·算法·机器学习·计算机视觉·语言模型
加农炮手Jinx5 小时前
LeetCode 72. Edit Distance 题解
算法·leetcode·力扣
借雨醉东风5 小时前
程序分享--常见算法/编程面试题:旋转矩阵
c++·线性代数·算法·面试·职场和发展·矩阵
茅盾体5 小时前
汽车零件订单自动同步系统方案
python
_深海凉_5 小时前
LeetCode热题100-打家劫舍
算法·leetcode·职场和发展
2401_883600255 小时前
golang如何理解weak pointer弱引用_golang weak pointer弱引用总结
jvm·数据库·python
FreakStudio5 小时前
和做工厂系统的印尼老哥,复刻了一套属于 MicroPython 的包管理系统
python·单片机·嵌入式·大学生·面向对象·并行计算·电子diy·电子计算机
2301_773553626 小时前
mysql如何评估SQL语句的索引开销_mysql性能追踪与分析
jvm·数据库·python
jghhh016 小时前
使用 MATLAB 实现支持向量回归 (SVR) 预测未来数据
算法·matlab
云泽8086 小时前
笔试算法 - 双指针篇(二):四大经典求和题型 + 有效三角形计数问题
c++·算法