How to Swap two numbers without using third ?
Page 1 of 1
How to Swap two numbers without using third ?
There are many possible solution to this problem . I will discuss each of them and would also point out the flaws in them.
1. SUM/PRODUCT /DIVISON /MULTIPLICATION
Method:
a. a= a+b
b=a-b
a=a-b
problem : if a in an integer(2 bytes in c), the highest number that it can sttore is 2^16. Now if a is (2^16 - 5) and b is (2^16 - 10) then a+b will result in overflow. Thus this method is not suitable for large values of a and b
b. a=a*b
b=a/b (Now, b =(a*b)/b = a)
a=a/b (Now, a =(a*b)/a = b)
problem : the above problem is also applicable for thi solution also but one major problem with this if one of the number is zero ,then it may lead to divide by zero error.
2. XOR
solution:
a = a ^ b
b = b ^ a
a = a ^ b
* ^ stands for xor
problem: this solution doestn't work if one of the number is zero as well for situation when both a and b are equal.
3. Embedded Statement
Solution:
a = a + b - (b = a)
problem : Till date i have not come across any case in which this fails and is probably the best possible solution to this problem.
Please post in your comments !!!!
1. SUM/PRODUCT /DIVISON /MULTIPLICATION
Method:
a. a= a+b
b=a-b
a=a-b
problem : if a in an integer(2 bytes in c), the highest number that it can sttore is 2^16. Now if a is (2^16 - 5) and b is (2^16 - 10) then a+b will result in overflow. Thus this method is not suitable for large values of a and b
b. a=a*b
b=a/b (Now, b =(a*b)/b = a)
a=a/b (Now, a =(a*b)/a = b)
problem : the above problem is also applicable for thi solution also but one major problem with this if one of the number is zero ,then it may lead to divide by zero error.
2. XOR
solution:
a = a ^ b
b = b ^ a
a = a ^ b
* ^ stands for xor
problem: this solution doestn't work if one of the number is zero as well for situation when both a and b are equal.
3. Embedded Statement
Solution:
a = a + b - (b = a)
problem : Till date i have not come across any case in which this fails and is probably the best possible solution to this problem.
Please post in your comments !!!!
Page 1 of 1
Permissions in this forum:
You cannot reply to topics in this forum
|
|