Thursday 13 August 2015

Check number is even or odd without division

We can do this by using bitwise & operator. If number is even, then last bit of its is zero, if the number is odd, then last bit of its is 1.

public class NumberCheck {

 public static boolean isEven(int num){
  return ((num&1)==0);
 }
}


Following is the junit test case for above program.
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class NumberCheckTest {

 @Test
 public void test1() {
  assertTrue(NumberCheck.isEven(0));
  assertTrue(NumberCheck.isEven(2));
  assertTrue(NumberCheck.isEven(4));

  assertFalse(NumberCheck.isEven(1));
  assertFalse(NumberCheck.isEven(3));
  assertFalse(NumberCheck.isEven(5));

 }
}


No comments:

Post a Comment