用 O(1) 时间检测整数 n 是否是 2 的幂次。
样例
Example 1:
Input: 4
Output: true
Example 2:
Input: 5
Output: false
挑战
O(1) time
思路:当数为2的幂次时,二进制中除最高位其余位数均为1,当n-1时,与n对应的最高位为0,其余位数均为1,&使得结果为0,因此只需要判断n&n-1是否为0即可。
例:
4 | 00000100 |
---|---|
3 | 00000011 |
4&3=0 | 00000000 |
– | – |
class Solution {
public:
/**
* @param n: An integer
* @return: True or false
*/
bool checkPowerOf2(int n) {
// write your code here
if(n <= 0) return false;
return (n & (n - 1)) == 0;
}
};```