class Solution {
public:
bool isPowerOfTwo(int n) {
/* if(n <= 0)
return false;
if(n == 1)
return true;
if(n%2 == 1)
return false;
return isPowerOfTwo(n/2);*/
return n>0 && !(n&(n-1));//发现可知,2的幂指数数据二进制位都是高位为1,后面为0;减1后为高位为0,后面为1,按位与结果肯定为0;
}
};
[leetcode 231]Power of Two
最新推荐文章于 2024-07-12 21:04:18 发布