Using O(1) time to check whether an integer n is a power of 2.
Have you met this question in a real interview? Yes
Example
For n=4, return true;
For n=5, return false;
Challenge
O(1) time
n&(n-1) 1的个数
n-n&(n-1) 末位1
class Solution {
/*
* @param n: An integer
* @return: True or false
*/
public boolean checkPowerOf2(int n) {
// write your code here
if(n<1) return false ;
else return (n&(n-1))==0;
}
};