Understanding a better solution Q19 (num & 1)
hi...so I've attempted this question with what I thought was an elegant solution :)...
def don_odd_even(num):
if (num % 2) == 0:
print('Even')
else:
print('Odd')
...but reviewing Giles' solution...
def odd_even(num):
if (num & 1):
print('Odd')
else:
print('Even')
... I'd like to understand how the '&' operator achieved the same functionality as the modulus function used in my attempt.
Warm regards,
-don
Hey Don,
Thank you for your question!
Your solution is indeed great! What Giles makes use of are bitwise operators.
If you execute on a new line the following:
42 & 1
you will get 0. If you instead execute the following:
43 & 1
you will get 1. Typing any odd number before & will result in 1, while trying any even number before the & will return 0. Since 1 corresponds to True
, while 0 corresponds to False
, you will print out 'Odd'
for odd numbers and 'Even'
for even numbers.
Think of the &
operator as binary multiplication. By applying &
to num
and 1
, it is implied that you are multiplying them in binary. In binary, all even numbers end with a 0, while all odd numbers end with a 1. This means that multiplying the former by 1 would return a 0, while multiplying the latter by 1 would return a 1.
You can use the following syntax to convert decimal numbers in binary
bin(a)
where a
is any integer. You will quickly convince yourself that indeed all even numbers end with a 0, while all odd numbers end with a 1.
Hope this helps!
Kind regards,
365 Hristina