题目地址:
https://leetcode.com/problems/power-of-two/description/
给定一个整数 n n n,问其是否是 2 2 2的幂次。
首先必须 n > 0 n>0 n>0,然后用lowbit即可。代码如下:
class Solution {
public:
bool isPowerOfTwo(int n) {
return n > 0 && n == (n & -n);
}
};
时空复杂度 O ( 1 ) O(1) O(1)。