[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
        
相关推荐
一个不知名程序员www9 小时前
算法学习入门 --- 哈希表和unordered_map、unordered_set(C++)
c++·算法
jaray9 小时前
PyCharm 2024.3.2 Professional 如何更换 PyPI 镜像源
ide·python·pycharm·pypi 镜像源
Psycho_MrZhang9 小时前
Neo4j Python SDK手册
开发语言·python·neo4j
Sarvartha9 小时前
C++ STL 栈的便捷使用
c++·算法
web3.08889999 小时前
1688图片搜索API,相似商品精准推荐
开发语言·python
少云清10 小时前
【性能测试】15_JMeter _JMeter插件安装使用
开发语言·python·jmeter
夏鹏今天学习了吗10 小时前
【LeetCode热题100(92/100)】多数元素
算法·leetcode·职场和发展
光羽隹衡10 小时前
机器学习——TF-IDF实战(红楼梦数据处理)
python·tf-idf
飞Link10 小时前
深度解析 MSER 最大稳定极值区域算法
人工智能·opencv·算法·计算机视觉
bubiyoushang88810 小时前
基于CLEAN算法的杂波抑制Matlab仿真实现
数据结构·算法·matlab