[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
        
相关推荐
编程见习者2 分钟前
【ReAct企业数据文件分析助手】
人工智能·python
Shaoshing4 分钟前
LeetCode100 152.乘积最大子数组
数据结构·算法·leetcode
吞下星星的少年·-·8 分钟前
力扣 162. 寻找峰值(枚举,二分查找)
算法·leetcode·枚举·二分
风落青芜15 分钟前
C++模板初阶:函数模板与类模板
开发语言·数据结构·c++·算法
纪念 22924 分钟前
C++ 算法模板与错题 (枚举)
c++·redis·算法
FYKJ_201027 分钟前
springboot网上汽车租赁系统93523-计算机毕业设计、课程设计
java·vue.js·spring boot·后端·python·汽车·课程设计
梅雅达编程笔记41 分钟前
向量库选 Chroma 还是 Milvus:RAG 智能问答毕设选型完整教程
python·智能问答·milvus·毕设·向量数据库·chroma·rag
汤姆宝库1 小时前
GraphRAG:把语料抽成图谱再回答全局问题的完整做法
开发语言·python·机器学习
蓝博AI9 小时前
2027基于yolov8飞机蒙皮缺陷检测,支持图像,视频和摄像实时检测,python源码
开发语言·python·yolo
是菜鸡小小陈啊9 小时前
【CS329Z Assignment 1】从零构建 LLM Agent Harness(学习笔记)08
笔记·python·学习·大模型·llm