位运算的题,Power of two转化成2进制的话只可能是某一位是1其余为0,我们只需要用n&(n - 1)检测即可,这个运算可以每次消去n的最低为1的位,我们只需检测运算后结果是否为0即可,O(1)时间复杂度,代码如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
bool isPowerOfTwo(int n) { | |
if(n <= 0)return false; | |
return !(n & (n - 1)); | |
} | |
}; |
No comments:
Post a Comment