Compare Two numbers without using or =

I came across this problem of comparing two numbers without using any kind of comparison operator(comparison operator implies <,>,=)

A wonderful solution to this problem which I came across  is given below—

For some funny reason which I have yet to find, d>>(sizeof(int)*8-1) gives a -1 on ideone when d is negative.But otherwise it works fine and gives a 0 when d is positive.

#include<iostream>

using namespace std;

int main()

{

 int a,b,c,d;

 cout<<"Enter numbers to be compared";

 cin>>a>>b;

 d=a-b;

 c=a+(d>>(sizeof(int)*8-1))*d;
 cout<<"The larger number is "<<c<<"\n";
 return 0;

}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s