Saturday, December 15, 2018

Swapping 2 number without using temp variable

Hello Guys,

Will see ,how to swap 2 numbers in java without using temp variable.


Algo to swap number
--------------------

int a =10;
int b=20;

a=a+b; // which is 30
b=a-b;// now a is 30 and b is 20 so result is 10
a=a-b; now b is 10 and a is 30 so result is 20

Swapping using XOR bitwise operator
----------------------------------
int p=10;
int q=20;

//X^Y is equal return 0 or and if its not equal than return 0
p=p^q;
q=p^q;//here p=q
p=p^q;//here q=p



Thanks,
Vikas