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

Rafay picture Rafay · Aug 1, 2017 · Viewed 10.8k times · Source

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 ..

Answer

Sergio Muriel picture Sergio Muriel · Aug 1, 2017

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

return 1 - value;