[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
        
相关推荐
田梓燊5 小时前
力扣:23.合并 K 个升序链表
算法·leetcode·链表
invicinble6 小时前
这里对java的知识体系做一个全域的介绍
java·开发语言·python
re林檎6 小时前
算法札记——4.27
算法
m0_674294646 小时前
如何编写SQL存储过程性能对比_记录执行时间评估优化效果
jvm·数据库·python
数据牧羊人的成长笔记7 小时前
逻辑回归与Softmax回归
算法·回归·逻辑回归
运气好好的7 小时前
怎样开启phpMyAdmin的操作审计日志_记录每条执行的SQL
jvm·数据库·python
郑州光合科技余经理7 小时前
同城O2O海外版二次开发实战:从支付网关到配送算法
开发语言·前端·后端·算法·架构·uni-app·php
2401_871492858 小时前
Layui如何修改Layui默认的UI主题颜色(换肤功能实现)
jvm·数据库·python
南子北游8 小时前
Python学习(基础语法1)
开发语言·python·学习
步辞8 小时前
Redis如何利用LFU算法优化缓存命中率
jvm·数据库·python