Search code examples
javamethodsbinarybooleanbitwise-operators

When input is 0 output is 1 and output is 0 when input is 1 in java


Write a method which will pass only one integer(1 or 0) as parameter. It will return 0 when input is 1 and return 1 when input is 0. The catch is we cannot use any operator*. I tried this approach. any other way available? Thanks in advance.

public BigInteger process(int i){
        BigInteger bi = BigInteger.valueOf(i);
        BigInteger one =BigInteger.valueOf(1);
        return bi.xor(one);
    }

Solution

  • You could invert the value using an array sorted backwards.

    public int invert(int i) {
        int[] ints = {1, 0};
        return ints[i];
    }
    

    EDIT: Here it is with a little error handling:

    public int invert(int i) {
        try {
            int[] ints = {1, 0};
            return ints[i];
        } catch (ArrayIndexOutOfBoundsException e) {
            System.err.println("invert(int) was called with value " + i + ". Expected values are 0 and 1.");
            e.printStackTrace();
        }
    }
    

    As Ole pointed out in the comments the ArrayIndexOutOfBoundsException triggered when reading from a non-existing array cell is technically enough to prevent method misuse, but it does not hurt to deliver a little bit of additional debug information.