Swapping 2 numbers is one of the basic question asked in the interviews or read in the syllabus.
What is Swapping?
Interchanging the values of two variable i.e. if a = 10 and b = 15, it becomes a = 15 and b = 10.
In this article, we will discuss 3 approaches in swapping 2 number.
Approach 1: (Swap using a temporary variable)
We will take a temporary variable, store the value of a in the temporary variable, copy the value of b to a and then store
temp = a
a = b
b = temp
Complete source code can be found here.
Approach 2: (Swap without using temporary variable)
In this Approach we will not use any extra variable, we will store the sum of both the variable in one of the first number. Then subtract the second number from the sum and store it in second number (sum - second = first) and then subtracting the second number from sum and store in first number (sum - second(which has become first now) = second)
a = a+b
b = a-b (here b gets the value of a)
a = a-b (here a gets the value of b)
Complete source code can be found here.
Approach 3: (Swap without using temporary variable using bit-wise operator)
In this approach we will use the concept
a^b = x (lets say)
x^a = b, and
x^b = a
so we store the xor of a and b in a itself and do alternatively xor and store it back
lets say a=10, b=5
a = a^b // a = 10^5
b = a^b // b = 10^5^5 => 10
a = a^b // a = 10^5^10 => 5
you can find the code here
Please provide your feedback.
What is Swapping?
Interchanging the values of two variable i.e. if a = 10 and b = 15, it becomes a = 15 and b = 10.
In this article, we will discuss 3 approaches in swapping 2 number.
Approach 1: (Swap using a temporary variable)
We will take a temporary variable, store the value of a in the temporary variable, copy the value of b to a and then store
temp = a
a = b
b = temp
Complete source code can be found here.
Approach 2: (Swap without using temporary variable)
In this Approach we will not use any extra variable, we will store the sum of both the variable in one of the first number. Then subtract the second number from the sum and store it in second number (sum - second = first) and then subtracting the second number from sum and store in first number (sum - second(which has become first now) = second)
a = a+b
b = a-b (here b gets the value of a)
a = a-b (here a gets the value of b)
Complete source code can be found here.
Approach 3: (Swap without using temporary variable using bit-wise operator)
In this approach we will use the concept
a^b = x (lets say)
x^a = b, and
x^b = a
so we store the xor of a and b in a itself and do alternatively xor and store it back
lets say a=10, b=5
a = a^b // a = 10^5
b = a^b // b = 10^5^5 => 10
a = a^b // a = 10^5^10 => 5
you can find the code here
Please provide your feedback.
No comments:
Post a Comment