Compare two integers without using any Comparison operator

Given two integers A & B. Task is to check if A and B are same or not without using comparison operators.

Examples:

Input : A = 5 , B = 6
Output : 0

Input : A = 5 , B = 5 
Output : 1

Note : 1 = "YES" and 0 = "NO"

idea is pretty simple we do Xor of both element ( A , B ) . if Xor is zero then two number are equal else not .
Below c++ implementation of above idea

// C++ program to compare two integers witout
// any comparison operator.
#include<bits/stdc++.h>
using namespace std;

// function return true if A ^ B > 0  else false 
bool EqualNumber(int A, int B)
{
   return ( A ^ B ) ;
}

// Driver program 
int main()
{
  int A = 5 , B = 6; 
  cout << !EqualNumber(A, B) << endl; 
  return 0;
} 

Output:

0

Reference :http://stackoverflow.com/questions/476800/comparing-two-integers-without-any-comparison


This article is contributed by Nishant Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice





Writing code in comment? Please use code.geeksforgeeks.org, generate link and share the link here.