How to create a method to return 1 or 0 without using conditions?

Rafay :

I was asked a question in an interview to return 1 if provided 0 and return 0 if provided 1 without using conditions i.e if, ternary etc

Just to give you and idea below code without if's:

public int testMethod(int value){
    if(value==0) return 1;
    if(value==1) return 0;
    return 0;
}

Java Fiddle

UPDATE: Though @Usagi's Answer may seem the best fit with respect to the code I wrote .. but re-considering the question I re-analyzed the answers .. and @Sergio's answer seems the simplest and best fit ..

Sergio Muriel :

If you are given only 0 and 1 then this could be simpler:

return 1 - value;

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=429418&siteId=1
Recommended