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