[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
        
相关推荐
算法鑫探15 小时前
闰年判断:C语言实战解析
c语言·数据结构·算法·新人首发
yaoxin52112315 小时前
384. Java IO API - Java 文件复制工具:Copy 示例完整解析
java·开发语言·python
Greyson115 小时前
Layui表格如何使用第三方插件实现树形展示.txt
jvm·数据库·python
WBluuue15 小时前
数据结构与算法:康托展开、约瑟夫环、完美洗牌
c++·算法
2401_8716965215 小时前
mysql行级锁失效的原因排查_检查查询条件与执行计划
jvm·数据库·python
木子墨51615 小时前
LeetCode 热题 100 精讲 | 并查集篇:最长连续序列 · 岛屿数量 · 省份数量 · 冗余连接 · 等式方程的可满足性
数据结构·c++·算法·leetcode
xzal1216 小时前
python中,turtle基础知识笔记1
笔记·python·turtle
a95114164216 小时前
CSS如何实现元素隐藏不占位_使用display-none完全移除
jvm·数据库·python
rabbit_pro16 小时前
Python调用onnx模型
开发语言·python