Solution 1 - Single Set Bit Check
A positive power of two has exactly one set bit, so n & (n - 1) is zero.
A positive power of two has exactly one set bit, so n & (n - 1) is zero.
""" 0231.1 - Power of Two - Solution 1 - Single Set Bit Check """
#####################################################################################
# Imports
#####################################################################################
#####################################################################################
# Classes
#####################################################################################
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n > 0 and (n & (n - 1)) == 0
#####################################################################################
# Functions
#####################################################################################
def testcase():
assert Solution().isPowerOfTwo(1)
assert Solution().isPowerOfTwo(16)
assert not Solution().isPowerOfTwo(3)
print("tests passed")
#####################################################################################
# Main
#####################################################################################
if __name__ == "__main__":
testcase()/** 0231.1 - Power of Two - Solution 1 - Single Set Bit Check */
/////////////////////////////////////////////////////////////////////////////////////
// Classes
/////////////////////////////////////////////////////////////////////////////////////
class Solution {
isPowerOfTwo(n: number): boolean {
return n > 0 && (n & (n - 1)) === 0;
}
}
console.log(new Solution().isPowerOfTwo(16)); // true