In Java XOR with three true inputs returns true. Why?

前端 未结 7 1011
一个人的身影
一个人的身影 2021-02-08 00:42

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:         


        
相关标签:
7条回答
  • 2021-02-08 01:21
    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
    
    0 讨论(0)
  • 2021-02-08 01:25

    Think about how the compiler evaluates this:

    (true ^ true) ^ true
    

    After first term true ^ true, which is false, has been evaluated:

    (false) ^ true ==> true
    
    0 讨论(0)
  • 2021-02-08 01:25

    '^' is a binary logical operator, not an n-ary operator.

    0 讨论(0)
  • 2021-02-08 01:29

    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.

    0 讨论(0)
  • 2021-02-08 01:30

    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)
    
    0 讨论(0)
  • 2021-02-08 01:32

    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.

    0 讨论(0)
提交回复
热议问题