leetcode代码已经放入github:[https://github.com/gaohongbin/leetcode](https://github.com/gaohongbin/leetcode)
题目:Given an integer, write a function to determine if it is a power of two.
翻译:给你一个整型,写一个函数来确定它是否是2的幂。
思路:(1)这个题如果用一直对2取模,再除以2,看最后能不能等于1。
这个思路写下来在leetcode上会超时。
(2)根据位运算,如果一个数是2的幂,那么它的二进制表示中只有一位是1,其他全是0。
而(N&(N-1))就是把N的二进制表示的最右边一位1变为0.
所以如果一个数N是2的幂,则(N&(N-1))==0.
代码:
public boolean isPowerOfTwo(int n) {
return n > 0 && ((n & (n - 1)) == 0 );
}