Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - How to exchange the values of two integer variables without introducing a third variable?
How to exchange the values of two integer variables without introducing a third variable?
XOR means to judge whether two corresponding bit values are different. If they are different, the true value is 1, otherwise it is false 0. Using XOR can realize positioning flip:

10 10

1 1 1 1(^)

——————

0 10 1

That effect can be achieved by using this principle.

If a = 3 and b = 4, to exchange their values, you can use a = a b, b = b a, and a = a b.

a=0 1 1

b= 100

^

——————

a= 1 1 1

b= 100

^

———

b=0 1 1

a= 1 1 1

^

——————

a= 100

Execute the first two assignment statements, a = a b, b = b a, which is equivalent to b (a b), and b a b = a b b b b equals 0, so b = a 0, b = 3.

Then execute the third statement, a = a b, because a = (a b) and b = (b a b), which is equivalent to

A = ABB ABB, that is, A = ABB ABB equals B.

A equals the original value of B.

namely

a=a^b= 1 1 1

b=b^a= 100^ 1 1 1=0 1 1

a=a^b= 1 1 1^0 1 1= 100=3