Given an integer, write a function to determine if it is a power of two.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
[思路]
如果是power of two, 則2進制表達中,有且僅有一個1. 可以通過移位來數1的個數, 這裡用了一個巧妙的辦法, 即判斷 N & (N-1) 是否為0.
[CODE]
public class Solution { public boolean isPowerOfTwo(int n) { return n > 0 && ((n & (n - 1)) == 0 ); } }