当输入为 0 时输出为 1,当输入为 1 时输出为 0 in java

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

编写一个只传递一个整数(1 或 0)作为参数的方法。当输入为 1 时它将 return 0,当输入为 0 时它将为 return 1。要注意的是 我们不能使用任何运算符 *。 我试过这种方法。还有其他方法吗?提前致谢。

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

您可以使用向后排序的数组反转值。

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

编辑:这里有一些错误处理:

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();
    }
}

正如 Ole 在评论中指出的那样,从不存在的数组单元格读取时触发的 ArrayIndexOutOfBoundsException 在技术上足以防止方法误用,但传递一些额外的调试信息也无妨.