Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the following code do?

Tags:

java

i = i + j ;
j = i - j ;
i = i - j ;

What the above code do ? Can someone write the same operation with other code ?

thnx.

like image 820
Batman Avatar asked Feb 28 '11 17:02

Batman


1 Answers

It's a technique to swap the values of i and j without creating a temporary variable. It's a form of memory optimization

If you're interested in learning about some of these things, I found a site about swapping values:

http://booleandreams.wordpress.com/2008/07/30/how-to-swap-values-of-two-variables-without-using-a-third-variable/

Another way to swap values is with the bitwise operator Exclusive Or (XOR)

a = a ^ b

b = a ^ b

a = a ^ b

This way is my favorite personally because it's more fun to think about conceptually. Integers are sets of bits, (ones and zeros)

a 64 bit integer has 64 "ones and zeros"

The ones and zeros are binary.

1 = 1

10 = 2

11 = 3

100 = 4

101 = 5

111 = 6

That's an example of binary to decimal. Now the bitwise operator XOR works like flipping a switch. So:

2 ^ 1 = 3 :binary: 10 ^ 01 = 11

and

3 ^ 2 = 1 :binary: 11 ^ 10 = 01 = 1

Now now that you understand that, you can see how swapping variables with it might work out.

Let's set a = 3 and b = 2 (in binary) and try it

a = 100

b = 10

a = a ^ b :: a = 100 ^ 10 = 110

b = a ^ b :: b = 110 ^ 10 = 100

a = a ^ b :: a = 110 ^ 100 = 10

now a = 10 and b = 100 or a = 2 and b = 3

Welcome to bits!

like image 116
Dbz Avatar answered Oct 01 '22 09:10

Dbz