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里有趣的解法:
参考:
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);