Swap Two Numbers - IMPORTANT FOR INTERVIEWS














































Swap Two Numbers - IMPORTANT FOR INTERVIEWS



In interviews many times tricky questions like swapping two numbers without using extra variables is being asked by interviewers.
In python we can directly swap numbers without using extra space(variable)

#Swap two numbers
first = 10
second = 20
first,second = second,first
print(first)
print(second)

Output:
20
10

But this might not impress interviewers because this is python supported and they might want general solution i.e language independent. So you may use code given below

#Swap two numbers
first = 10
second = 20

first = first+second     #first = 30
second = first-second #second = 30-20 = 10
first = first-second     #first = 30-10 = 20
print(first)
print(second)

Output:
20 
10





Comments