0

I had been asked to provide the java implementation of the following pseudo code:

function 
{
    Input n; //can have either of the two values : 10 or 20
    if n == 10
        return 20
    else
        return 10
}

I tried following :

int function(int n){
    if (n == 10){
        return 20;
    }
    return 10;
}

Now the next one:

int function (int n){
    return n == 10 ? 20 : 10;
}

Here is another one (an extreme one-liner):

int function (int n){
    return 30 - n;
}

But, the question asker had some more technique (in a single line), in his mind and I wonder what that might be!
Any idea?

Draken
  • 3,134
  • 13
  • 34
  • 54
singhan
  • 27
  • 2
  • What is your question now? – Sayakiss May 24 '16 at 08:51
  • The question is as asked above, If there is any other way to achieve the result. – singhan May 24 '16 at 08:52
  • There are infinite number of ways to achieve the desired result. – 1615903 May 24 '16 at 08:53
  • This is a too broad / opinion-based question, which isn't suited for Stack Overflow. Please refer to [ask] and the [help/on-topic]. – Tunaki May 24 '16 at 08:56
  • Indeed too broad, another possibility is that he would have liked you to check the validity of the input (*e.g.* throw an exception if the input is neither 10 nor 20) – danbanica May 24 '16 at 09:00
  • @qwertyman: I had got that cleared by the examiner. He was mostly concerned about the logic to derive the result. Input validation was absolutely not his concern. ! – singhan May 24 '16 at 09:05
  • The last example does not seem to fulfill the requirements of the pseudo code. –  May 24 '16 at 09:33
  • Yes it does @wonko79, `if n == 10 then return 20`, 30 - 10 = 20. And the other one is `if n == 20 then return 10` and 30-20 = 10. The pseudo code states: `Input n; //can have either of the two values : 10 or 20` – Draken May 24 '16 at 11:18
  • Yes you ar right. I didn't saw the comment with the constraint of n. –  May 24 '16 at 11:31

1 Answers1

2

You could use bit-shift operators :

return n==10?n<<1:n>>1;

or multiplication/division :

return n==10?n*2:n/2;
Eran
  • 387,369
  • 54
  • 702
  • 768