Swapping two numbers using bit manipulation involves a technique that makes use of XOR (^) operator. The XOR operator has a unique property where if you XOR any number with itself, the result is 0, and if you XOR any number with 0, the result is the number itself. This property allows swapping without a temporary variable. Here’s how it works:
Let’s say we have two variables a and b and we want to swap their values without using a temporary variable.
- First, we XOR
aandband store the result back ina. After this operation,acontains the result ofa XOR b. - Then, we XOR
bwith the newa(which isa XOR b). Since XORingbwitha XOR bcancels outb, we are left with justa, so nowbcontains the original value ofa. - Lastly, we XOR
a(which is stilla XOR b) with the newb(which now holds the original value ofa). This cancels out the originalafroma XOR b, leaving us with justb, so nowacontains the original value ofb.
Kotlin
fun main() {
var a = 5 // Example value for a
var b = 7 // Example value for b
println("Before swap: a = $a, b = $b")
// Step 1: XOR a and b, store the result in a
a = a xor b
// Step 2: XOR the new a (which is a xor b) with b, store the result in b
b = a xor b
// Step 3: XOR the new b (which now contains the original value of a) with the new a (a xor b), store the result in a
a = a xor b
println("After swap: a = $a, b = $b")
}Explanation:
a = a xor b: This line XORsaandband stores the result back ina. The XOR operation produces a unique combination of bits fromaandbthat, when XOR’d with eitheraorbagain, can produce the other value.b = a xor b: Now thatacontainsa xor b, XORing it withbeffectively “cancels out” the bits ofb(becauseb xor b = 0anda xor 0 = a), leaving the original value ofa, which is then stored inb.a = a xor b: At this point,bholds the original value ofa, andaholdsa xor b. XORing these gives us the original value ofb, which is stored ina.
The key to understanding this method is recognizing the properties of the XOR operation. XORing two identical numbers results in 0, and XORing a number with 0 results in the original number. These properties allow the swap to happen without a temporary variable.