Thursday, August 28, 2008

How to find whether a given number is even or odd without using % (modulus) operator ?

A newbie question. Here is a simple C++ solution.

bool isOdd(int num){
return num&1?true:false;
}


If the number is odd then it's least significant bit (LSB) is set i.e. it is 1. If it is even then it is 0. When you bitwise and (&) this number with 1, the result would be either 1 if the number is odd or zero if it is even.

As rightly pointed out by SpS, the same code can be implemented in C (following C99 standard) as

#include
bool isOdd(int num){
return (num&1)?true:false;
}


Here stdbool.h defines the macros bool, true and false. The macro bool is defined to be _Bool (the boolean type according to C99 standard). true is a macro which expands to the decimal constant 1 and false is a macro which expands to decimal constant 0.

For C89 sticklers

int isOdd(int num){
return (num&1);
}


You can use the returned value to determine if the number is odd or not. If the value returned is 0, the number is even. It is odd otherwise.