+ 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
7 Answers
+ 7
a=a+b b=a-b a=a-b any language
28th Jan 2023, 7:54 PM
Prashanth Kumar
Prashanth Kumar - avatar
+ 7
In python, it's very easy. a, b = b, a Swapped ✅️
28th Jan 2023, 7:49 PM
Ausgrindtube
Ausgrindtube - avatar
+ 3
xor swap x = x ^ y y = y ^ x x = x ^ y Of course this should only be used with integers since XOR with floating point numbers are either unsupported or floored depending on the language.
28th Jan 2023, 8:03 PM
「HAPPY TO HELP」
「HAPPY TO HELP」 - avatar
+ 1
I understand that you may be inquiring about the method of swapping the values of two variables without the use of a third variable, as a means of expanding your understanding of programming techniques. Alternatively, it appears you may also be bringing to our attention a common practice used by job interviewers in asking such questions. Please clarify which of these intentions is the case, so that I may better assist you.
28th Jan 2023, 7:52 PM
Mirielle
Mirielle - 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
Sammy Raven
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