Skip to content

Commit 4658682

Browse files
committed
Given an integer, write a function to determine if it is a power of two
1 parent 2ee5db1 commit 4658682

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

231-power-of-two.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
"""
2+
Given an integer, write a function to determine if it is a power of two.
3+
4+
Example 1:
5+
Input: 1
6+
Output: true
7+
8+
Example 2:
9+
Input: 16
10+
Output: true
11+
12+
Example 3:
13+
Input: 218
14+
Output: false
15+
"""
16+
class Solution(object):
17+
def isPowerOfTwo(self, n):
18+
return n > 0 and not(n & n-1)
19+
20+
"""
21+
Explanation:
22+
At a power of 2, we only have one bit set to 1 at its respective decimal place (e.g. 1000).
23+
At the power of 2 minus 1, we have all the bits before the current decimal place set to 1 (e.g. 0111), which means that n & (n - 1) == 0
24+
for powers of 2.
25+
The reason why this happens is because we're in the binary number system and a power of 2 means we're going to the next decimal place
26+
(i.e. 0111 + 1 = 1000).
27+
28+
What about when n is not a power of 2? If you look at a list of binary numbers:
29+
0100
30+
0101
31+
0110
32+
0111
33+
1000
34+
35+
Remember how the power of 2 is the special case where adding 1 results in us moving to the next decimal place (i.e. 0111 + 1 = 1000)?
36+
Since every other case doesn't result in that, there is at least the current power of 2's 1 bit overlapping with whatever the number
37+
is (i.e. we're at 0100, 0101 will always share the 0100 bit. The only time the 0100 bit becomes 0 again is if we go to the next power of 2).
38+
"""

0 commit comments

Comments
 (0)