File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed
Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change 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+ """
You can’t perform that action at this time.
0 commit comments