t题目:
Given an integer n
, return true
if it is a power of two. Otherwise, return false
.
An integer n
is a power of two, if there exists an integer x
such that n == 2x
.
Example 1:
Input: n = 1 Output: true Explanation: 20 = 1
Example 2:
Input: n = 16 Output: true Explanation: 24 = 16
Example 3:
Input: n = 3 Output: false
Constraints:
-231 <= n <= 231 - 1
Follow up: Could you solve it without loops/recursion?
题解:
2的n次方很容易会联想到二进制数。
例如: = 1 对应二进制 1
= 2 对应二进制 10
= 4 对应二进制 100
依次类推,同时由于二进制特性,这些数减一后都变为首位为0,后面全为1。
例如-1(十进制) = 3(十进制) = 011(二进制),
所以4和3的逻辑与为0。
列用此特性,我们可以利用 (n & (n - 1)) == 0 来进行判断是否满足题目要求。
//参考程序
class Solution {
public:
bool isPowerOfTwo(int n) {
if (n <= 0) return false; //边界条件限定
return ((n & (n - 1)) == 0); //逻辑与
}
};
其他方法参考链接:[LeetCode] Power of Two 判断2的次方数 - Grandyang - 博客园(讲的很好)