[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
        
相关推荐
计算机编程-吉哥21 分钟前
脑肿瘤MRI智能识别系统:基于深度学习的像素级脑肿瘤语义分割平台【计算机毕业设计选题推荐】
人工智能·python·深度学习·算法·毕业设计·课程设计·大数据毕业设计选题推荐
小木_.24 分钟前
Python 离线识别滑块缺口距离,项目推荐
开发语言·python·滑块识别·人机验证·滑块缺口·缺口识别
Cenxi31 分钟前
Python字符串方法练习手册
人工智能·python
liliangcsdn36 分钟前
因子权重矩阵处理-因子权重收缩Shrinkage算法的探索
开发语言·python·机器学习
用户83562907805143 分钟前
使用 Python 在 Excel 中添加和编辑形状
后端·python
用户204937554951 小时前
端侧语音部署踩坑:模型能跑不等于终端真的能用
后端·算法
2601_962300471 小时前
python在运维上可以干什么,请举几个具体的例子
运维·python·系统管理·网络监控·自动化脚本
shehuiyuelaiyuehao1 小时前
算法39,位运算,消失的两个数字
java·数据结构·算法
ZiLing1 小时前
2026 ROS 2 Lyrical 踩坑实录(一):编译与依赖——rosdep、现代 CMake 与 CMake 4.x
算法
小刘在重生~1 小时前
Java 异常体系完整笔记
java·笔记·python