+ 2
How can I check if a variable is even or odd?
Is there a smart way to decide if an integer is even or odd?
6 Réponses
+ 7
If you are looking for even faster way compared to using modulo operator, then just make use of the fact that bitwise AND of any number with 1 will either give 1 (if the LSB or least significant bit of the number is 1{odd number}) or 0 otherwise
Check this out (using python as it is taged language) 👇
https://code.sololearn.com/cypGtpqyYZEv/?ref=app
+ 7
Mathias Andersson keep on learning to reduce the pain 👍
+ 5
Another thing is to use the result as boolean
if n%2:
# ODD
else:
# EVEN
# Or make an even/odd switch (I saw this from Jan Markus).
print( [ "even", "odd" ] [n%2] )
If even the the result of n%2 will become 0 then the 0 will be the index of the list, then it will get the value "even", same mechanics when odd.
+ 4
Hi Mathias Andersson
Using the remainder operator is the fastests way i know and it is covered in the course so maybe look at that or search as similar questions have been asked before
https://www.sololearn.com/learn/JUMP_LINK__&&__Python__&&__JUMP_LINK/4430/
https://code.sololearn.com/ci941j06WrI6/?ref=app
https://www.sololearn.com/Discuss/2252811/?ref=app
+ 4
if n % 2 == 0:
EVEN
else:
ODD
+ 2
Thanks guys. I had the right idea, but wrong execution. The pain is real.