leetcode-231-Power-of-Two

描述


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

分析


判断一个数是不是2的n次幂,以前写过这样的题目,跟leetcode-326-Power-of-Three(补上地址)类似,不过3的n次幂那道题有一种hack的做法。当然这里也可以用位操作来解决

解决方案1(C++)


1
2
3
4
5
6
7
class Solution {
public:
bool isPowerOfTwo(int n) {
double logres = log10(n) / log10(2);
return logres == int(logres)? true: false;
}
};

位操作:

1
2
3
4
5
6
7
8
9
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n <= 0) {
return false;
}
return (n & (n-1)) == 0;
}
};

解决方案2(Python)


1
2
3
4
5
6
7
8
9
10
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
if n <= 0:
return False

return n&(n-1) == 0;

相关问题


(E) Power of Three
(E) Number of 1 Bits

题目来源