Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning the other argument of 2 possible arguments without using conditions [closed]

Tags:

java

For example, if I have a function that is guaranteed to receive either 5 or 7 as an argument, I want the function to return 5 if received 7 and 7 if received 5 without using any conditions.

I was asked this in an interview and was pretty stumped, thanks.

like image 689
davegri Avatar asked Feb 24 '13 20:02

davegri


1 Answers

Simple arithmetic:

return 7 - input + 5;

(which can be simplified as return 12 - input;)

Let's say the input is 7:

return 7 - 7 + 5 --> return 5

Or if the input is 5:

return 7 - 5 + 5 --> return 7

like image 148
Simon Forsberg Avatar answered Sep 20 '22 17:09

Simon Forsberg