【python3】leetcode 231. Power of Two (easy)

本文探讨了多种高效算法来判断一个给定的整数是否为2的幂次方,包括数学计算、二进制位操作及按位与运算。这些方法不仅适用于LeetCode题目231.PowerofTwo,还展示了Python编程技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

231. Power of Two (easy)

Given an integer, write a function to determine if it is a power of two.

Example 1:

Input: 1
Output: true 
Explanation: 20 = 1

Example 2:

Input: 16
Output: true
Explanation: 24 = 16

Example 3:

Input: 218
Output: false

这道题很简单 主要记一下一些有意思的解法

1 我自己写的,很中规中矩,反向检查

class Solution(object):
    def isPowerOfTwo(self, n):
        """
        :type n: int
        :rtype: bool
        """

        return n>0 and n == 2**int(math.log(n,2))

1.1关于类似的写法我发现一个

return n>0 and math.log(n,2).is_integer()

但是这个不通过(1107/1108),n = 536870912时,我在ipython里测了一下是 29.000000000000004,浮点溢出了。。

但是换成log2又可以,。,,神奇

return n>0 and math.log2(n).is_integer()

后面的是从discussion里看到的

 2 这个也比较容易理解 ,就是二进制判断,2的幂都是1开头,后面一串0(如1,10,100,1000等)

return n > 0 and bin(n).count("1") == 1

3 使用按位与 比如4 的二进制是100,3的二进制是011,4 & 3 = 100 & 011 = 000 = 0

interesting,因为2^n一定是1000...., 2^n -1 一定是01111...,所以相与一定是0

return n > 0 and n&(n-1) == 0

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值