BuzzTalk
Would you like to react to this message? Create an account in a few clicks or log in to continue.

How to Swap two numbers without using third ?

Go down

How to Swap two numbers without using third ? Empty How to Swap two numbers without using third ?

Post  Admin Sun Aug 17, 2008 6:34 am

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 !!!!
Admin
Admin
Admin

Number of posts : 37
Registration date : 2008-08-08

https://buzztalk.1talk.net

Back to top Go down

Back to top


 
Permissions in this forum:
You cannot reply to topics in this forum