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

18,133

Solution 1

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

return 1 - value;

Solution 2

public int testMethod(int value) {
  return 1 - (value % 2); // or 1 - (value & 1)
}

This could use to switch between any value and 0, EG 3:

public int testMethod3(int value) {
  return 3 - (value % 4);
}

And just to cover the return 0 at the end of the sample in the question:

private static final int[] VALUES = { 1, 0 };

public int testMethod(int value) {
    try {
        return VALUES[value];
    } catch (ArrayIndexOutOfBoundsException ex) {
        return 0;
    }
}

Solution 3

We can use the xor operator here. Xor is "exclusive or" and returns a 0 when there are two or zero 1's and returns 1 if there's exactly one 1. It does this on every bit of the integer.

So for example, the binary 1001 ^ 1000 = 0001 as the first bit has two 1's, so 0, the next two have no 1's, so zero, and the final bit only has one 1, outputting a 1.

public int testMethod(int value){
    return value ^ 1;
}

Solution 4

My original answer

public int TestMethod(int value)
{
     return Convert.ToInt32(!Convert.ToBoolean(value));
}

and the modified one as suggested by @The Photon

public int TestMethod(int value)
{
     return Convert.ToInt32(value == 0);
}

A different approach is based on the behaviour of integer division in C# and avoiding the usage of exception handling.

public int TestMethod(int value)
{
    return 1 / ((10 * value) + 1);
}

All three methods will return the same results:

In | Out
-2 | 0 
-1 | 0
 0 | 1
 1 | 0
 2 | 0 

Solution 5

You can use a bitwise operator like so:

value ^ 1

^ is the bitwise XOR operator which "copies the bit if it is set in one operand but not both". The representation of 1 and 0 in bits is as follows:

1 = 0000 0001

0 = 0000 0000

So when value = 1 you end up doing:

1 ^ 1 = (0000 0001) ^ (0000 0001) = 0000 0000 = 0 because since they share the same bits none of the bits are copied over.

Now if value = 0 you end up doing:

0 ^ 1 = (0000 0000) ^ (0000 0001) = 0000 0001 = 1 because the last bit is 1 in one of the operands but 0 in the other.

Share:
18,133
Rafay
Author by

Rafay

A Software Engineer by profession .. Wish to learn more ..

Updated on June 03, 2022

Comments

  • Rafay
    Rafay almost 2 years

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