Swapping A and B without 3rd variable
yubaraj singh
Posted on January 13, 2021
So my teacher gave me a task, a simple task to swap two values in our new Java class. That was an easy task as we had a good background in the Programming language. But he stated that no more than two elements were allowed. That seems a tricky one and everyone in the class was clueless cause this was the mathematical approach for solving.
So it was a bit confusing and after finding a solution I was a bit surprised as there was indeed a better technique for swapping.
steps
* add a and b and assign to a
* subtract a from b and assign to b
* subtract a from b and assign to a
Now, this became our simple swapping without using the third parameter.
Here is a code in java.
class SwapTest {
public static void main(String arg[]) {
int a = 999999999;
int b = 999999999;
a = a + b;
b = a - b;
a = a - b;
System.out.println("a=" + a + " b=" + b);
}
}
disadvantage of this method in java is that while using integer it will overflow when the number is large
Posted on January 13, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.