Given an integer, write a function to determine if it is a power of two.html
Example 1:spa
Input: 16
Output: true
Example 2:code
Input: 5 Output: false
判斷一個數是否爲2的次冪,偶然發現3年前作這道題就是很簡單的循環對2取餘整除。順手用位運算寫了一行代碼又提交了一次。效率提高了200多倍。
public boolean isPowerOfTwo(int n) { return n > 0 && (n & (n - 1)) == 0; }
原理參考這篇博客的技巧部分。htm