Recipe 1.5 Test for an Even or Odd Value
Problem
You need a simple method to test a numeric
value to determine whether it is even or odd.
Solution
The solution is actually implemented as two methods. To test for an
even integer value, use the following
method:
public static bool IsEven(int intValue)
{
return ((intValue & 1) == 0);
}
To test for an odd integer value, use the following
method:
public static bool IsOdd(int intValue)
{
return ((intValue & 1) == 1);
}
Discussion
Every odd number always has its least-significant bit set to
1. Therefore, by checking whether this bit is
equal to 1, we can tell whether it is an odd
number. Conversely, testing the least-significant bit to see whether
it is 0 can tell you whether it is an even number.
To test whether a value is even we AND the value
in question with 1 and then determine whether the
result is equal to zero. If the result is zero, we know that the
value is an even number; otherwise, the value is odd. This operation
is part of the IsEven method.
On the other hand, we can determine whether a value is odd by
ANDing the value with 1,
similar to how the even test operates, and then determine whether the
result is 1. If the result is set to
1, we know that the value is an odd number;
otherwise, the value is even. This operation is part of the
IsOdd method.
Note that you do not have to implement both the
IsEven and IsOdd methods in
your application, although implementing both methods might improve
the readability of your code.
The methods presented here accept only 32-bit integer values. To
allow this method to accept other numeric data types, you can simply
overload it to accept any other data types that you require. For
example, if you need to also determine whether a 64-bit integer is
even, you could modify the IsEven method as
follows:
public static bool IsEven(long longValue)
{
return ((longValue & 1) == 0);
}
Only the data type in the parameter list needs to be modified.
|