Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to swap without a third variable?

Tags:

variables

c#

I have to swap two variables with a number value without using a third variable. What is the simple solution?

like image 833
Student Avatar asked Mar 17 '11 20:03

Student


People also ask

How do you swap without variables?

Given two variables, x, and y, swap two variables without using a third variable. The idea is to get a sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from the sum.

Can u swap two numbers without using 3rd variable?

Swapping two variables without using a third variable. The arithmetic operators for addition and subtraction can be used to perform the swap without using a third variable. Similarly, multiplication and division can be used to perform the swap without using the third variable.

How do you swap 4 numbers without using a third variable?

You could use the XOR swap on successive pairs, to swap n variables without a temp variable.


2 Answers

Let us see one of the method namely by using arithmetic operators. Consider 2 variables say x=50 and y=70 and let us see how to swap the value of two variables that is make x=70 and y=50 without using third variable. This can be done by using following arithmetic operations namely
x= x + y
y= x - y
x= x - y
Which gives
• x= x + y gives x= 70 + 50 an so x is equal to 120
• y= x - y gives y = 120 - 70 which makes the value of y as 50
• x= x - y gives x= 120 - 50 and thus value of x becomes 70

like image 100
Student Avatar answered Sep 18 '22 01:09

Student


You can achieve it with XOR

int A = ...;
int B = ...;
A = A ^ B;
B = A ^ B;
A = A ^ B;
like image 42
Fede Avatar answered Sep 19 '22 01:09

Fede