5 DIFFERENT WAYS TO SWAP TWO NUMBERS
Hi friends, here I'm posting 5 different ways to swap two numbers using any programming language like C,C++,Java etc.
1. // Easy n native way swapping using three variables (Takes extra memory space)
int a=2, b=5, c;
c=a;
a=b;
b=c;
2. // using arithmetic operations
a=a+b;
b=a-b;
a=a-b;
3. // using bit-wise operations
a=a^b;
b=b^a;
a=a^b;
4. // one line statement using bit-wise
operators
//Most efficient way, less time consumption
a^=b^=a^=b;
//Same as 3 in on line
5. // Most tricky way, one line way of 1
a=(a+b) - (b=a);
Comments
Post a Comment