[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
        
相关推荐
凌冰_28 分钟前
数据结构 - 数组(八)
数据结构·算法·矩阵
惯兰高手38 分钟前
信阳政务系统开发的消息通知功能实际设计要注意什么?
python
16月6日-晴43 分钟前
122. 买卖股票的最佳时机 II【贪心】
算法·leetcode
kyh10033811201 小时前
从仿生学到深度学习:人工神经网络原理解析
人工智能·python·深度学习
承渊政道1 小时前
【Python编程快速上手—让繁琐工作自动化】(组织文件:用Python批量改名,把整个文件夹打包备份)
开发语言·python·pycharm·自动化·文件整理·组织文件
Darkwanderor1 小时前
在 Win11 和 CentOS 7.6 安装Python 3.12.7 的流程和踩坑记录
python·腾讯云·python安装·踩坑记录
Shaoshing2 小时前
LeetCode 1798. 你能构造出连续值的最大数目
java·数据结构·算法
Metaphor6922 小时前
使用 Python 轻松调整 Word 文档的页边距
python·word·页边距
大今野2 小时前
江苏专转本计算机大类基础理论考点:算法的概念与复杂度分析
数据结构·算法·专转本
郝学胜-神的一滴2 小时前
量化交易从入门到精通 04:量化生意的四大特点
开发语言·数据结构·c++·python·算法·pycharm