8.15 练手 腾讯50题 231

本文提供了一种使用位运算判断一个整数是否为2的幂的方法,通过分析整数在二进制表示下的特性,提出了一种高效算法,并分享了一个达到100%通过率的Python实现。同时,文章还介绍了讨论区的两种有趣解法,包括二进制法和数学法。

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

Leetcode 231. Power of Two

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

 

想法是因为整数是按照二进制记录的,因此使用位运算判断,不是2的幂次数的整数的特点:

1. 为0 或者 负数

2.右移的时候(整除2的时候),整数出现 最后一位为1 并且 左边的剩余位还有1 的情况,举个例子:

3  =>  11  =2+1 = 2^1 +1

12=> 110 =8+4 = 2^3 +2^2 +0

代码如下:

class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        #n is Integer 不需要考虑幂为负数情况(即n为小数)
        #但是要考虑 n <= 0的情况
        output = False
        if(n <= 0):
            return False
       
        while(n>0):  
            if(n&1 == 1 and (n>>1)>0):
                return False
            else:
                n = n>>1
        output = True   
        return output

Beat 100% 

虽然是个简单题,但是是第一次的100%有点开心。

 

Discuss里有趣的解法:

参考:

https://leetcode.com/problems/power-of-two/discuss/63966/4-different-ways-to-solve-Iterative-Recursive-Bit-operation-Math

1.二进制法

关键点是前后两个数有没有进位,如果后面一个数加一进位了说明就是2的整数次幂了

class Solution {
public:
    bool isPowerOfTwo(int n) {
        if(n<=0) return false;
        return !(n&(n-1));
    }
};

2.数学法

用 2^30 // n 看是不是整数,解析如下:

Because the range of an integer = -2147483648 (-2^31) ~ 2147483647 (2^31-1), the max possible power of two = 2^30 = 1073741824.

(1) if n is the power of two, let n = 2^k, where k is an integer.

We have 2^30 = (2^k) * 2^(30-k), which means (2^30 % 2^k) == 0.

(2) If n is not the power of two, let n = j*(2^k), where k is an integer and j is an odd number.

We have (2^30 % j*(2^k)) == (2^(30-k) % j) != 0.

return n > 0 && (1073741824 % n == 0);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值