Given an integer, write a function to determine if it is a power of two.
Example 1:
Input: 1 Output: true Explanation: 20 = 1
Example 2:
Input: 16 Output: true Explanation: 24 = 16
Example 3:
Input: 218 Output: false
题目大意:
给出一个数判断其是否为2的次方幂。
解题思路:
我们发现2的次方幂都具有以下特征:
2-10 4-100 8-1000 .....
所以我们发现当这个数与比其小一的数进行&运算时会产生0,如果不是则不会产生0。
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n<1) return false;
return n & (n-1) ?false:true;
}
};