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
a
andb
and store the result back ina
. After this operation,a
contains the result ofa XOR b
. - Then, we XOR
b
with the newa
(which isa XOR b
). Since XORingb
witha XOR b
cancels outb
, we are left with justa
, so nowb
contains 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 originala
froma XOR b
, leaving us with justb
, so nowa
contains 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 XORsa
andb
and stores the result back ina
. The XOR operation produces a unique combination of bits froma
andb
that, when XOR’d with eithera
orb
again, can produce the other value.b = a xor b
: Now thata
containsa xor b
, XORing it withb
effectively “cancels out” the bits ofb
(becauseb xor b = 0
anda xor 0 = a
), leaving the original value ofa
, which is then stored inb
.a = a xor b
: At this point,b
holds the original value ofa
, anda
holdsa 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.