版权声明:来自 T2777 ,请访问 https://blog.csdn.net/T2777 一起交流进步吧 https://blog.csdn.net/T2777/article/details/86767039
题目:
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的幂,这里找到规律:
1 = 2^0=1b, 2 = 2^1= 10b, 4 = 2^2=100b, 8 = 2^3=1000b
当为2的幂时,发现 n 与 n-1相与以后得到的是0,而其他不为2的幂,则结果不为0。
如: 100与011相与得到0,1000与0111相与得到0
而101与100相与结果为100,111与110相与得到110
c++中&是按位相与,得到的结果并不是在0与1中选一,而是各种各样的数
代码为:
class Solution {
public:
bool isPowerOfTwo(int n) {
if( n <= 0)
return false;
return ((n&(n-1)) == 0);
}
};