[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
        
相关推荐
Benny_Tang3 分钟前
「雅礼集训 2018 Day7」A 题解
数据结构·c++·算法
计算机源码社5 分钟前
【大数据项目实战】基于K-Means的科技公司裁员特征分群与规模信号挖掘系统 基于数据挖掘的科技企业裁员事件异常检测与可视化研究
大数据·python·数据挖掘·毕业设计·kmeans·课程设计·数据可视化
IT毕设实战小研6 分钟前
基于大数据的跨国外派人员适应满意度与留存影响因素可视化分析
android·java·大数据·python·django·课程设计
Doubbbbbbble云13 分钟前
跳表结构在高并发系统中的应用与优势分析4
算法
TAN-90°-14 分钟前
Deep Learning for Computer Vision——Large Scale Distributed Training
人工智能·深度学习·神经网络·算法·机器学习·计算机视觉·语言模型
Lyyaoo.24 分钟前
【回溯】【中等】全排列
java·数据结构·算法
写后端的胖头鱼28 分钟前
一文讲懂JVM与调优
jvm·后端·算法·架构·jvm调优
步行cgn30 分钟前
Spring Boot 指定数据来源详解
spring boot·后端·python
土司大王36 分钟前
LeetCode 79 单词搜索:Java 回溯模板、网格 DFS 与剪枝优化
java·算法·leetcode·深度优先
ECT-OS-JiuHuaShan41 分钟前
哲学是迭代学,数学是拓扑学
开发语言·人工智能·学习·算法·机器学习·php·拓扑学