231 - Power of Two
Written on October 21, 2015
Tweet
Given an integer, write a function to determine if it is a power of two.
class Solution {
/*
* @param n: An integer
* @return: True or false
*/
public boolean checkPowerOf2(int n) {
// write your code here
if (n < 1 ) return false;
//n = 0 or n < 0 return false
//error check !!
else {
return ((n & (n - 1)) == 0);
}
}
};
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
return False if n <= 0 else (n & n - 1) == 0