+ 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?

27th Jan 2021, 12:44 AM
Mathias Andersson
Mathias Andersson - avatar
6 Antworten
+ 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
27th Jan 2021, 1:20 AM
Arsenic
Arsenic - avatar
+ 7
Mathias Andersson keep on learning to reduce the pain 👍
27th Jan 2021, 1:03 AM
Sonic
Sonic - avatar
+ 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.
27th Jan 2021, 1:49 AM
noteve
noteve - avatar
+ 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
27th Jan 2021, 12:57 AM
Ollie Q
Ollie Q - avatar
+ 4
if n % 2 == 0: EVEN else: ODD
27th Jan 2021, 12:58 AM
ChaoticDawg
ChaoticDawg - avatar
+ 2
Thanks guys. I had the right idea, but wrong execution. The pain is real.
27th Jan 2021, 12:59 AM
Mathias Andersson
Mathias Andersson - avatar