2

Possible Duplicate:
Find the maximum of two numbers without using if-else or any other comparison operator

isGreater:

if x > y  then return 1, else return 0 

Example:

  • isGreater(4,5) = 0
  • isGreater(5,4) = 1

Legal operators: ! ~ & ^ | + << >>

isGreater is the function..

I tried:

int isGreater(int x, int y) {
    return (y+(~x+1)) >> 31 & 1;
}

but not working.. :(( Let me know what else I can do?

11
  • 13
    What is with the endless stream of "how do I do X with some limited subset of the C operators?" type questions? Commented Jan 25, 2011 at 21:56
  • 4
    Step 1. Please format your code using the {} button. Step 2. Please mark your homework with the [homework] tag. Commented Jan 25, 2011 at 21:57
  • 1
    @Oli, it's a common homework assignment, apparently. Commented Jan 25, 2011 at 21:59
  • 1
    The title says "Maximum of two numbers" whereas the question itself suggests that you just want to test for x > y - which is it ??? Commented Jan 25, 2011 at 22:20
  • 2
    This is a reasonable homework assignment for a math class, not for a programming class. Commented Jan 26, 2011 at 5:29

2 Answers 2

0

given x, y

try x + -y if < 0 then y is greater, if > 0 then x is greater.

-y = binary complement of y:

-y = (~(y-1))
<==>
-y = (~y)+1

From what I see, you do the binary complement with (~y +1)), which is the same.

Then bitshift >> 31 to get the MSB, and equal to 1.
Make sure to set parantheses, operator precedence !

 (y+-x) >> (31 & 1);
!=
 ((y+-x) >> 31) & 1;
Sign up to request clarification or add additional context in comments.

1 Comment

@Paul apparently you didn't read his answer
0

Too easy -- since you have + in the list of legal operators, you can trivially synthesize - (as others have noticed) and thus do a subtract and extract the sign. Its much more interesting if you leave out + (as it isn't a bitwise operator anyways) and answer the question with just bitwise ops (& | ^ ~) and shifts.

Of course, you could synthesize +/- from the bitwise ops and shifts, but there's actually an easier way.

1 Comment

That restriction does make it more interesting, though I can't +1 in good conscience as you're really asking a separate question. The solution I have in mind requires 5 right-shifts, which I suspect is the minimum possible number.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.