題目地址:
https://www.lintcode.com/problem/o1-check-power-of-2/description
給定一個數,要求的時間判斷其是否爲的冪次。只需看其二進制表示中是否只有一個即可。但需要注意Integer.MIN_VALUE
也滿足這個條件,所以要判斷一下這個數要是正數。判斷其是否只含一個可以用lowbit來解決。其中lowbit(x) = x & -x
,指的是x
的二進制表示最右邊的所代表的十進制數是幾。這可以由-x = ~x + 1
得到。代碼如下:
public class Solution {
/**
* @param n: An integer
* @return: True or false
*/
public boolean checkPowerOf2(int n) {
// write your code here
return n > 0 && n == (n & -n);
}
}
時空複雜度。