Easy difficulty 276
Given an integer, write a function to determine whether it is a power of 2.
Example 1:
Input: 1 Output: true Explanation: 20 = 1Example 2:
Input: 16 Output: true Explanation: 24 = 16Example 3:
Input: 218 Output: false
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n == 0){
return false;
}
long x = n; //如果x = INT_MIN, x-1会产生溢出,转为位数更多的long 则不会检查溢出
return (x & (x-1)) == 0;
}
};
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n == 0){
return false;
}
long x = n; //如果x = INT_MIN, x-1会产生溢出,转为位数更多的long 则不会检查溢出
return (x & (-x)) == x;
}
};
How to get the rightmost 1: x & (-x)
How to set the rightmost 1 in binary to 0: x & (x-1)
I have stolen the picture, sorry hum~