以下代码
System.out.println("1 0 0: " + (true ^ false ^ false));
System.out.println("1 0 1: " + (true ^ false ^ true));
System.out.println("1 1 0: " + (true ^ true ^ false));
System.out.println("1 1 1: " + (true ^ true ^ true));
System.out.println("0 0 0: " + (false ^ false ^ false));
System.out.println("0 0 1: " + (false ^ false ^ true));
System.out.println("0 1 0: " + (false ^ true ^ false));
System.out.println("0 1 1: " + (false ^ true ^ true));
输出:
1 0 0: true
1 0 1: false
1 1 0: false
1 1 1: true
0 0 0: false
0 0 1: true
0 1 0: true
0 1 1: false
当所有三个输入均为
true
时,为什么XOR返回true
?如果输入的元素之一是
true
(无论我提供多少输入),那么如果它是有效的逻辑,如何实现只返回的逻辑? 最佳答案
If you want a true result, if one and only one inputs is true you can use:
(a ^ b ^ c ) ^ ( a && b && c )
the test case result:
true true true = false
true true false = false
true false true = false
true false false = true
false true true = false
false true false = true
false false true = true
false false false = false