Friday 26 February 2016

Swapping of two numbers without using third variable

Approach#1.
Addition and Subtraction Method

Integer a, b
read a and b
a= a+b;
b=a-b;
a=a-b;

Problem:
Incorrect result when sum of numbers will exceed the Integer range.


Approach#2. 
Multiplication and Division Method

Integer a, b
read a and b
a=a*b;
b=a/b;
a=a/b;

Problems:
1. If the value of a*b exceeds the range of integer.
2. If the value of a or b is zero then it will give wrong results.

Approach#3.
XOR Method

Integer a , b
read a and b
a=a^b;
b=a^b;
a=a^b;

Best approach to solve this problem without any pitfalls.



No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...