[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 分钟前
如何解决 pip install 编译报错 fatal error: hdf5.h: No such file or directory(h5py)问题
人工智能·python·pycharm·开源·beautifulsoup·ai编程·pip
Mz12217 分钟前
day05 移动零、盛水最多的容器、三数之和
数据结构·算法·leetcode
SoleMotive.11 分钟前
如果用户反映页面跳转得非常慢,该如何排查
jvm·数据库·redis·算法·缓存
p***233611 分钟前
python的sql解析库-sqlparse
数据库·python·sql
念越18 分钟前
判断两棵二叉树是否相同(力扣)
算法·leetcode·入门
陈奕昆22 分钟前
n8n实战营Day1课时3:高频节点解析+Webhook表单同步Excel实操
人工智能·python·n8n
深蓝电商API30 分钟前
动态 Token、加密参数逆向全流程:从原理到实战破解
爬虫·python
qq_17082750 CNC注塑机数采30 分钟前
【Python TensorFlow】 TCN-GRU时间序列卷积门控循环神经网络时序预测算法(附代码)
python·rnn·神经网络·机器学习·gru·tensorflow·tcn
java1234_小锋38 分钟前
基于Python深度学习的车辆车牌识别系统(PyTorch2卷积神经网络CNN+OpenCV4实现)视频教程 - 切割车牌矩阵获取车牌字符
python·深度学习·cnn·车牌识别
u***28471 小时前
Python连接SQL SEVER数据库全流程
数据库·python·sql