[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
        
相关推荐
luoluoal1 分钟前
基于自适应svm电影评价倾向性分析
python·mysql·毕业设计·源码
zl_vslam2 分钟前
SLAM中的非线性优-3D图优化之绝对位姿SE3约束SO3/t形式(十八)
人工智能·算法·计算机视觉·3d
啊阿狸不会拉杆2 分钟前
《计算机操作系统》 - 第九章 操作系统接口
人工智能·算法·计算机组成原理·os·计算机操作系统
我送炭你添花3 分钟前
pytest 入门指南:从零开始掌握 Python 测试框架的核心概念与使用方法
chrome·python·pytest
dazzle3 分钟前
Python数据结构(六):双端队列详解
开发语言·数据结构·python
一起养小猫4 分钟前
Flutter for OpenHarmony 实战:碰撞检测算法与游戏结束处理
算法·flutter·游戏
刃神太酷啦5 分钟前
Linux 基础 IO 收官:库的构建与使用、进程地址空间及核心知识点全解----《Hello Linux!》(11)
java·linux·c语言·数据库·c++·算法·php
板面华仔5 分钟前
机器学习入门(一)——KNN算法
人工智能·算法·机器学习
玄同76512 分钟前
MermaidTrace库:让Python运行时“自己画出”时序图
开发语言·人工智能·python·可视化·数据可视化·日志·异常
开开心心就好15 分钟前
视频伪装软件,.vsec格式批量伪装播放专用
java·linux·开发语言·网络·python·电脑·php