LeetCode : Is Power Of Two
Question :
https://leetcode.com/problems/power-of-two/description/
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n > 0 and (n & (n - 1)) == 0
n>0 : Simply dictates that zero and negative numbers are not accepted.
(n & (n - 1)) == 0 : This condition is here to do the magic trick. When you do a bitwise AND (&) of the number and number-1, and it equals zero then the number is power of 2.
Idea : The main idea behind this approach is “Powers of 2 only have 1-bit in binary“. When you have let’s say 8 → 1000 (has only 1 set bit) and then you have 8-1 = 7 → 0111 (this is the flip of bits from original number 8→1000, if you carefully observe). And when when we do a bitwise and between both we are bound to get zero and if we get zero it will mean the binary form of the original number had only 1 set bit to begin with and hence it will be a power of two.
Thank You