+ 3
How to swap no.s without using 3rd variable?
Any language is preferred.
9 Respuestas
+ 18
Umm... Representing the python community here...
.
.
.
.
.
.
.
.
.
.
.
x,y=y,x
+ 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/]
+ 9
num1 = 10
num2 = 2
num1=num1-num2;
num2=num1+num2;
num1=num2-num1;
+ 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.
+ 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
+ 3
Thnx for ur answers guys.....
+ 1
use this
{ int a=20,b=5;
a=a+b;
b=a-b;
a=a-b;}
+ 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;