问题
The following code
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));
outputs:
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
Why does XOR returns true
when all three inputs are true
?
If it's valid logic how can I implement logic that returns true
only if one of the input elements is true
(no matter how many inputs I provide)?
回答1:
If you want a true result if one and only one input 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
回答2:
Because true xor true = false, and false xor true is true. xor is associative, so group the values any way you please!
To decide that only one of them is true, you could add the values together as integers and see if the answer is 1.
I'm answering this as a general programming question, it really isn't particular to Java.
回答3:
Think about how the compiler evaluates this:
(true ^ true) ^ true
After first term true ^ true
, which is false
, has been evaluated:
(false) ^ true ==> true
回答4:
Here's a Java 8 way of determining if exactly one boolean is true:
Stream.of(b1, b2, b3, ...)
.filter(b -> b)
.count() == 1;
回答5:
true ^ true ^ true
can be written (for understanding) as ( true ^ true ) ^ true
which is true
.
If A, B, C are inputs, for the logic that you are looking for, you need something like this
(A & !B & !C) | (!A & B & !C) | (!A & !B & C)
回答6:
'^' is a binary logical operator, not an n-ary operator.
回答7:
I don't know is it discovered and highlighted, but I noticed a thing that if we add all values together (no matter how many are there) and see what's left after division by 2 we can notice the result is false
if 0
left and true
if 1
left.
Example:
1 ^ 0 ^ 1 ^ 1 = 1
and
(1+0+1+1)%2 = 1
They are the same. Please, correct or guide me who has a clue about this case.
来源:https://stackoverflow.com/questions/6222162/in-java-xor-with-three-true-inputs-returns-true-why