Swap Two Numbers
Explore how to swap two numbers without traditional swapping logic by using the bitwise XOR operator. Understand and apply an efficient solution that operates in constant time and space, enhancing your algorithm skills focused on bit manipulation.
We'll cover the following...
We'll cover the following...
Introduction
In this question, input two numbers and swap them without using the swapping logic.
Problem statement
We need to write a program to swap two numbers.
Input: a = 10, b = 121
Output: a = 121, b = 10
Solution
We can make use of XOR to swap two values. You will find the solution below:
Complexity analysis
Time Complexity: We are not running a loop or scaling the inputs. The inputs never change. So the operation takes a single unit of time, which is .
Space Complexity: We didn’t create an extra memory for this. So, the space complexity is .