Sunday, 1 May 2016

How to swap 2 numbers without using 3rd variable ?


Solution #1. Addition and Subtraction method
a = a+b;
b = a-b;
a = a-b;

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


Solution #2. Multiplication and Division method
a = a*b;
b = a/b;
a = a/b;

Problem. Same problem with multiplication result
                Additionally, Incorrect result when a or b is 0


Solution #3. XOR method
a = a^b;
b = a^b;
a = a^b;

Best approach without any problem

No comments:

Post a Comment

Note: only a member of this blog may post a comment.