for n in [7, 12, 16, 1, 30, 64]:
parity = "odd" if n & 1 else "even" # last bit 1 means odd
power = n > 0 and n & (n - 1) == 0 # a power of two has one 1-bit
print(f"{n:>3}: {parity:<4} power of two: {power}")
Output Verified by running it on Python 3
7: odd power of two: False
12: even power of two: False
16: even power of two: True
1: odd power of two: True
30: even power of two: False
64: even power of two: True
n & 1 reads the lowest bit. n & (n - 1) clears the lowest set bit, so it is 0 only when exactly one bit was set.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!