XOR, or exclusive OR, is a fascinating operation in the realm of bit manipulation. Unlike the standard OR operation, which returns 1 for both bits being 1 or one of them being 1, XOR only returns 1 when the bits are different. Here’s a quick look at the truth table for XOR:
A (Bit 1) | B (Bit 2) | A XOR B |
---|---|---|
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 0 |
This property of XOR becomes particularly useful when we want to swap numbers without the need for a temporary variable, making it a clever trick that’s not just a party trick but has practical applications in programming.
Let's say you have two variables, a
and b
, and you want to swap their values. Using a temporary variable, you would typically do the following:
temp = a a = b b = temp
But we can achieve the same result using only bitwise XOR operations!
The steps to swap a
and b
using XOR are as follows:
Step 1: Perform XOR and assign the result to a
:
a = a ^ b
Step 2: Perform XOR with the new value of a
and assign it to b
:
b = a ^ b
Step 3: Perform XOR again to retrieve the original value of a
:
a = a ^ b
Let's look at these steps in action with a practical example.
Suppose we have a = 5
(which is 0101
in binary) and b = 3
(which is 0011
in binary).
Initial Values:
a = 5 (0101)
b = 3 (0011)
Step 1: a = a ^ b
a = 0101
b = 0011
a ^ b = 0110 (which is 6 in decimal)
a
: 6 (0110)
Step 2: b = a ^ b
a = 0110
b = 0011
a ^ b = 0101 (which is 5 in decimal)
b
: 5 (0101)
Step 3: a = a ^ b
a = 0110
b = 0101
a ^ b = 0011 (which is 3 in decimal)
a
: 3 (0011)
a = 3
b = 5
The values have been swapped without using a temporary variable!
O(1)
, making it efficient in terms of time complexity.By mastering how XOR operations can manipulate bits at a low level, you're equipping yourself with a tool that not only beautifies your code but also enhances your understanding of computer science fundamentals.
13/10/2024 | DSA
08/12/2024 | DSA
15/11/2024 | DSA
06/12/2024 | DSA
23/09/2024 | DSA
16/11/2024 | DSA
15/11/2024 | DSA
06/12/2024 | DSA
08/12/2024 | DSA
13/10/2024 | DSA
06/12/2024 | DSA