Fog Creek Software
Discussion Board




Compare 2 integers without comparision operators

How to compare 2 integers without using a
comparision operator?

Dave M
Tuesday, May 06, 2003

for signed integers, check the sign bit after subtraction.
For unsigned integers, check the highest bit that is on before subtraction.

Yichi Lu
Tuesday, May 06, 2003

a XOR a = 0

Matthew Wilson
Monday, May 12, 2003

Isn't that a comparison at the end?

Somebody
Wednesday, May 14, 2003

If the question is about finding the greater of the two, we can do like this:

max(a,b) = (a+b) - abs(a-b)
                  --------------------
                            2

Similarly for min add the two expressions in the numerator part.

Mind you. This wont work if a and b are of different sign

Eswar Bala
Friday, May 30, 2003

that gives you the min, not the max. to get the max you would add the abs instead of subtract.

jamie
Monday, June 02, 2003

"Isn't that a comparison at the end?"

If you think about it, you HAVE to use a comparison at the end. When you intend to do one thing in one case and another thing in another, you're going to need a comparison to find out which way to go. I have to assume the questioner meant not DIRECT comparisons, but you could perform some computation and evaluate the result of that.

Brad Wilson (dotnetguy.techieswithcats.com)
Tuesday, June 17, 2003

*  Recent Topics

*  Fog Creek Home