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
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
No comments:
Post a Comment