【LeetCode】231 - Power of Two

时间:2021-12-27 09:12:32

Given an integer, write a function to determine if it is a power of two.

Solution:一个整数如果是2的整数次方,那么它的二进制表示中有且只有一位是1,而其他所有位都是0。把这个整数与这个整数减去1之后进行与运算,那么这个整数当中唯一的1会变为0,这个整数也变为0

 class Solution {
public:
bool isPowerOfTwo(int n) {
if(n<=)return false;
return !(n&(n-));
}
};