Monday 3 August 2015

Check whether two integers are equal without using comparison operator


public class EqualityCheck {

 private static boolean result[] = { true };

 public static boolean isEqual(int num1, int num2) {

  int out = num1 ^ num2;

  try {
   return result[out];
  } catch (Exception e) {
   return false;
  }
 }
}

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 EqualityCheckTest {

 @Test
 public void test1() {
  assertTrue(EqualityCheck.isEqual(10, 10));
  assertTrue(EqualityCheck.isEqual(-10, -10));
  assertFalse(EqualityCheck.isEqual(10, 0));
 }
}



No comments:

Post a Comment