
6 Techniques by which you can swap 2 numbers.
in this show i have shared the 6 ways by which you can swap 2 variables.
19 December, 2022
1
1
0
Contributors
(1) using third temporary variable (everyone knows!!)
temp = a
a = b
b = temp
(2) using + and - operators
b = a + b
a = b - a
b = b - a
(3) using bitwise operators
a = a ^ b
b = b ^ a
a = a ^ b
(4) using * and / operators
•
handle the number = 0 case here.
b = a * b
a = b / a
b = b / a
(5) using in-built swap() function
swap(a , b)
(6) one liner way
b = a - b + (a = b)