Given an integer, write a function to determine if it is a power of two.
思路:判断一个数是不是2的乘方,根据数字在电脑中以二进制存储的特点,2的乘方只有1位是1,其他位均为0
若n为2的乘方,则n-1与n的每一位都是不同的,因此n与n-1按位与的结果为0
<pre name="code" class="java">public class Solution {
public boolean isPowerOfTwo(int n) {//if n is power of 2 ,n just has one bit is 1
return n>0 && (n&(n-1))==0;
}
}