+ 1

Swapping the value of two variables without creating a third variable.

Once upon a time, they used to ask such a question during a job interview

28th Jan 2023, 7:48 PM
Sardor
6 Answers
+ 7
a=a+b b=a-b a=a-b any language
28th Jan 2023, 7:54 PM
Prashanth Kumar
Prashanth Kumar - avatar
+ 6
In python, it's very easy. a, b = b, a Swapped ✅
28th Jan 2023, 7:49 PM
Ausgrindtube
Ausgrindtube - avatar
+ 1
Depends on the type of the variables' data and the language. With operator overloading, you could create generic operators that handle joining and separating data types during swaps (probably with an underlying data structure to hold those values), which would be useful in cases where "a" is an int and "b" is a struct, or both are objects. In other languages, a function will likely help. The question isn't how to swap two integers, because that's the answer you're giving. This question is a test of your ability to see the whole problem and discuss it; to see the misalignment between the acceptance criteria of the task and the sampled code. This isn't a simple "give answer, get cookie" question, but rather a question to coax out communications and comprehension skills.
30th Jan 2023, 1:58 PM
Sam
0
a = 6 b = 5 print (a) print (b) b, a = a, b print (a) print (b)
28th Jan 2023, 7:54 PM
Sardor
0
C guy be like :v a^=b^=a^=b;
1st Feb 2023, 4:51 AM
Amine Laaboudi
Amine Laaboudi - avatar