Thanks:  0
Likes:  0
Dislikes:  0

# Thread: Swap values between two variables without a temp

1. ## Swap values between two variables without a temp

in 3 mins.....

Thats what I was given in a past phone interview. Given the time pressure for the task at hand....I gave it a shot but was stuck on an infinite loop of thoughts after coming up with the first step. so if you can do it in 3 mins its good, else its an easy task.

2. ## Re: Swap values between two variables without a temp

Which language?
Which datatype?

3. ## Re: Swap values between two variables without a temp

If datatype is integer

x=x+y
y=x-y
x=x-y

4. ## Re: Swap values between two variables without a temp

Nice!
It was a generic question with no specific language...I could only come up with a = a+b and then couldnt construct the logic within the 3 min window. Later on, I could build the subsequent steps.

5. ## Re: Swap values between two variables without a temp

depends on the language you are using.

in Python, it's as simple as:

<font class="small">Code:</font><hr /><pre>
x,y = y,x
</pre><hr />

(it doesn't matter what data types x and y are)

6. ## Re: Swap values between two variables without a temp

a = a XOR b
b = b XOR a
a = a XOR b

Only uses bitwise operations, so I guess this method works for all data types?

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•
Search Engine Optimisation provided by DragonByte SEO v2.0.36 (Pro) - vBulletin Mods & Addons Copyright © 2016 DragonByte Technologies Ltd.
vBulletin Optimisation provided by vB Optimise v2.6.4 (Pro) - vBulletin Mods & Addons Copyright © 2016 DragonByte Technologies Ltd.
BetaSoft Inc.
Digital Point modules: Sphinx-based search
All times are GMT -8. The time now is 01:46 PM.