+ 3

How to swap no.s without using 3rd variable?

Any language is preferred.

8th Oct 2017, 8:10 AM
Sixth Sense
Sixth Sense - avatar
9 Antworten
+ 18
Umm... Representing the python community here... . . . . . . . . . . . x,y=y,x
8th Oct 2017, 10:35 AM
Frost
Frost - avatar
+ 17
The bitwise XOR operator can be used to swap two variables. The XOR of two numbers x and y returns a number which has all the bits as 1 wherever bits of x and y differ. For example, XOR of 10 (In Binary 1010) and 5 (In Binary 0101) is 1111 and XOR of 7 (0111) and 5 (0101) is (0010). #include <stdio.h> int main() { int x = 10, y = 5; // Code to swap 'x' (1010) and 'y' (0101) x = x ^ y; // x now becomes 15 (1111) y = x ^ y; // y becomes 10 (1010) x = x ^ y; // x becomes 5 (0101) printf("After Swapping: x = %d, y = %d", x, y); return 0; } [http://www.geeksforgeeks.org/swap-two-numbers-without-using-temporary-variable/]
8th Oct 2017, 9:51 AM
Babak
Babak - avatar
+ 9
num1 = 10 num2 = 2 num1=num1-num2; num2=num1+num2; num1=num2-num1;
8th Oct 2017, 8:23 AM
Meharban Singh
Meharban Singh - avatar
+ 4
a = a*b; b = a/b; a = a/b; a = a+b; b = a-b; a = a-b; my favourite, a = a^b; b = a^b; a = a^b; these methods can be applied with or without references.
19th Mar 2018, 1:47 PM
Ajay Agrawal
Ajay Agrawal - avatar
+ 3
Look at this program in c++. I have simplified the code to the best. I hope everything will b clear to you. -Saurav https://code.sololearn.com/cbkjVO2GQUG5/?ref=app
8th Oct 2017, 8:13 PM
Saurav Priyadarshi
Saurav Priyadarshi - avatar
+ 3
Thnx for ur answers guys.....
8th Oct 2017, 9:22 PM
Sixth Sense
Sixth Sense - avatar
+ 1
use this { int a=20,b=5; a=a+b; b=a-b; a=a-b;}
8th Mar 2018, 5:41 PM
amit
amit - avatar
+ 1
a = a + b; b = a - b; a = a - b; //Or this, but this is incompatible with large integers! a = a * b; b = a / b; a = a / b; //Or XOR, it is the best in memory efficiency! a = a ^ b; b = a ^ b; a = a ^ b;
19th Mar 2018, 3:58 AM
Naveen Maurya
Naveen Maurya - avatar