[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
        
相关推荐
烁34718 分钟前
每日一题(小白)动态规划篇2
算法·动态规划
橘猫云计算机设计19 分钟前
基于django优秀少儿图书推荐网(源码+lw+部署文档+讲解),源码可白嫖!
java·spring boot·后端·python·小程序·django·毕业设计
互联网杂货铺26 分钟前
如何用Postman实现自动化测试?
自动化测试·软件测试·python·测试工具·测试用例·接口测试·postman
予安灵33 分钟前
一文详细讲解Python(详细版一篇学会Python基础和网络安全)
开发语言·python
南玖yy1 小时前
数据结构C语言练习(栈)
c语言·数据结构·算法
冷月半明1 小时前
Python项目打包指南:PyInstaller与SeleniumWire的兼容性挑战及解决方案
python·selenium
冷月半明1 小时前
《Pandas 性能优化:向量化操作 vs. Swifter 加速,谁才是大数据处理的救星?》
python·数据分析·pandas
阿镇吃橙子1 小时前
一些手写及业务场景处理问题汇总
前端·算法·面试
酱酱哥玩AI1 小时前
Trae编译器:实现多目标班翠鸟优化算法(IPKO)无人机路径规划仿真(Python版),完整代码
算法
蹦蹦跳跳真可爱5891 小时前
Python----机器学习(基于PyTorch的线性回归)
人工智能·pytorch·python·机器学习·线性回归