[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
        
相关推荐
宸津-代码粉碎机3 分钟前
Spring 6.0+Boot 3.0实战避坑全指南:5大类高频问题与解决方案(附代码示例)
java·数据仓库·hive·hadoop·python·技术文档编写
傻啦嘿哟3 分钟前
Python自动整理音乐文件:按艺术家和专辑分类歌曲
数据库·python·分类
weixin_462446238 分钟前
基于 Flask + lunar-python 的农历转换 API 实战(公历 ↔ 农历 / 干支 / 生肖 / 节日)
python·flask·节日
Xの哲學20 分钟前
从硬中断到 softirq:Linux 软中断机制的全景解剖
linux·服务器·网络·算法·边缘计算
weixin_5795996621 分钟前
编写一个程序,输入两个数字的加减乘除余数(Python版)
开发语言·python
liu****24 分钟前
02_Pandas_数据结构
数据结构·python·pandas·python基础
生信碱移28 分钟前
单细胞空转CNV分析工具:比 inferCNV 快10倍?!兼容单细胞与空转的 CNV 分析与聚类,竟然还支持肿瘤的亚克隆树构建!
算法·机器学习·数据挖掘·数据分析·聚类
RFCEO43 分钟前
用手机写 Python程序解决方案
开发语言·python·智能手机·qpython环境安装
0思必得044 分钟前
[Web自动化] Requests模块基本使用
运维·前端·python·自动化·html·web自动化
AAA简单玩转程序设计1 小时前
救命!Python 这些基础操作居然能省一半工作量
python