Easy programming puzzle

Joined
Sep 21, 2022
Messages
159
Reaction score
23
Variables X and Y hold integers.

Swap the values of X and Y without using a third variable.
Code:
X=(X xor Y)
Y=(X xor Y)
X=(X xor Y)
 
Joined
Jul 4, 2023
Messages
466
Reaction score
57
;)
Code:
X = X + Y  # Now X holds the sum of X and Y
Y = X - Y  # Subtract Y from the sum, so Y becomes the original X
X = X - Y  # Subtract the new Y (original X) from the sum, so X becomes the original Y

[ working code on-line ]
Python:
X = -5
Y = 2

print(f"X = {X}, Y = {Y}")

X = X + Y  # Now X holds the sum of X and Y
Y = X - Y  # Subtract Y from the sum, so Y becomes the original X
X = X - Y  # Subtract the new Y (original X) from the sum, so X becomes the original Y

print(f"X = {X},  Y = {Y}")
 
Last edited:

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,930
Messages
2,570,072
Members
46,522
Latest member
Mad-Ram

Latest Threads

Top