Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use XOR in Kotlin

Tags:

kotlin

I want to perform an XOR to find if one of two booleans a and b is true but not both. Searching for XOR in Kotlin gave me this answer

infix fun xor(other: Boolean): Boolean

Performs a logical xor operation between this Boolean and the other one. source

I'm still confused on how to implement this

like image 615
unknown1 Avatar asked Feb 07 '18 19:02

unknown1


2 Answers

It's an extension that can be invoked on any Boolean. You can use it like this:

true.xor(false)

or this:

true xor false

The last one works since the function is defined as infix.

Other similar extensions defined on Boolean are and, or and not:

//very useful example
true.not().or(true).and(false).xor(true)
like image 109
s1m0nw1 Avatar answered Sep 21 '22 19:09

s1m0nw1


find the single number in the array that every element has a duplicate except one.

var a = 0
for (i in numsArray){
    a = a xor i
}
return a

eg. input = [2,2,1] out = 1

like image 28
Smmy Sa Avatar answered Sep 21 '22 19:09

Smmy Sa