Using O(1)
time to check whether an integer n is
a power of2
.
Example
For n=4
, return true
;
For n=5
, return false
;
Challenge
O(1) time
若为2的幂次方,则只存在一位为1. 可以1)统计1的个数 2)与n-1做与运算,无相同位即为true
class Solution {
/*
* @param n: An integer
* @return: True or false
*/
public boolean checkPowerOf2(int n) {
if (n<=0) return false;
boolean res = ((n & (n-1)) == 0) ? true : false;
return res;
}
};