Check whether number is even or odd
A prompt method to determine if a number is even or odd applies the modulo operator number % 2
. An even number will yield a remainder of 0
:
Just swap in your number for number
.
Bitwise operation: the speed demon
The bitwise AND operator (x & 1)
, while a tad esoteric, can help speed up your even/odd checks:
Considering the least significant bit of an even number is 0
and 1
for odd, this method is not only fast, but also displays your in-depth understanding of binary representation.
Modulo vs Bitwise: a crash course
The Modulo Approach
The modulo operator %
finds the remainder after division of one number by another (referred to as the divisor):
Generally, any number yielding 0
with %2
is even.
The Bitwise Approach
The bitwise AND operator &
performs a binary AND operation:
With bitwise, we're essentially checking the last digit of the binary representation (least significant bit).
When to use each method: choose your weapon
-
Clarity: The modulo method is generally more recognizable and readable to most developers. Favor this method when readability triumphs.
-
Efficiency: In systems where performance is paramount, the bitwise method might give you the edge.
-
Learning curve: For learners, starting with modulo instills a solid foundation. Later on, bitwise serves as a cool trick up your sleeve.
Cracking the edge cases
Overflow blues
Especially with large numbers, the overflow issue with %
may give incorrect results. Never fear, bitwise gracefully sidesteps this.
The case of the negatives
Happily, both methods handle negative numbers accurately. It's advisible to run negative scenarios through your code tests.
Integer divisions’ oddities
Becareful with integer division - look out for accidental use of /
instead of %
. The former could lead to quotient quandary, not a remainder revelation.
The smallest of them all
The humble 0
is even, and 1
is odd. These edge cases often get overlooked, but could reveal code logic errors.
Was this article helpful?