Quantcast
Channel: Vince Vella's Blog
Viewing all articles
Browse latest Browse all 29

Swapping two variables without using a third

$
0
0
I came across an interesting algorithm ... the normal way how programmers swap values between two variables is by using a temporary third variable ... temp = x, x = y, y = temp. An interesting trick can actually do the same process without having to use a third variable, and this is done by using the XOR operator. Below I am showing how this can be done in java:


public static void main(String[] args) {
int x = 15;
int y = 20;
System.out.println(x+""+y);
x ^= y;
y ^= x;
x ^= y;
System.out.println(x+""+y);
}


Try it out !

Viewing all articles
Browse latest Browse all 29

Trending Articles