Tuesday, January 22, 2013

Even or Odd

How to find out whether a given number is even or odd?

Traditional way:

int number = 10;

if(number%2 == 0){
System.out.println("Even number");
}else{
System.out.println("Odd number");
}

Output:
Even number

But what we an interviewer asks, not to use operator (%). Then we will be in trouble :).

Enhanced way:

public class EvenOrOddNumber {
 public static void main(String[] args) {

  System.out.println(isEvenNumber(10));
  System.out.println(isEvenNumber(13));

 }
 public static boolean isEvenNumber(int number){
  return (number & 1) == 0 ? true : false;
 }
}

Output:
true
false