LearnFrenzy
Sign in Take a free test

Operators and Expressions · Operators Coding Problems · Question 1

Even or odd and power of two using bitwise operators in Python Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

For each number in a list, print whether it is even or odd using the bitwise AND operator, and whether it is a power of two.

Solution
main.py Run
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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links