- To swap 2 numbers using XOR operator
User Input
1st number: 3
2nd number: 5
After Swap, Output:
1st number : 5
2nd number : 3
import java.util.Scanner
fun main(args: Array<String>) {
print("Enter 1st number : ")
val userInput = Scanner(System.`in`)
var n1:Int = userInput.nextInt()
print("Enter 2nd number : ")
var n2:Int =userInput.nextInt()
n1 = n1 xor n2
n2 = n2 xor n1
n1 = n1 xor n2
print("After Swapping\n Value of 1st number : $n1 \n Value of 2nd number : $n2")
}
Enter 1st number : 7 Enter 2nd number : 15 After Swapping Value of 1st number : 15 Value of 2nd number : 7Program
We are using binary XOR operator (^)
//Lets take n1=7, n2=3
n1 = n1 xor n2 //Here n1=4, n2=3
n2 = n2 xor n1 //Here n1=4, n2=7
n1 = n1 xor n2 //Finally n1=3, n2=7
Remember : A B (A xor B) 0 0 0 0 1 1 1 0 1 1 1 0Concept
Coming Soon !
QuickIn order to succeed you must fail, so that you know what not to do the next time.