Saturday, August 16, 2014

Swap Two Numbers Without Using the Third Variable

There are 2 methods that can swap 2 numbers without using the third variable.

1--"+" and "-"

public void changeNumber(int a, int b) {
    a = a + b;
    b = a - b;
    a = a - b;
}

2--"^" (XOR)

public void changeNumber(int a, int b) {
    a = a ^ b;
    b = a ^ b;
    a = a ^ b;
}

The second method is pretty tricky.

No comments:

Post a Comment