[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 226
  • Last Modified:

changing variable values

Hi, I have  a question, which I solved but using 3 variables.. would like to see if its possible with only 2 variables?

the questions says, ask the user to input A and B then let the two variables exchange the values.. so if A is 10 and B is 5 >>> the result should be A = 5 and B = 10..
0
msaa
Asked:
msaa
  • 2
1 Solution
 
mtmikeCommented:
You can use the XOR trick:

a ^= b;
b ^= a;
a ^= b;

But most machines have an XCHG instruction so the third variable is optimized out anyway.
0
 
msaaAuthor Commented:
Thank you very much it really worked! but I have no clue whats going on? could you please explain it?
0
 
mtmikeCommented:
I will try...

It is based upon the fact the x ^ y ^ y = x, since y ^ y = 0 and x ^ 0 = x.

When you write the XOR sequence like this:

c = a ^ b
d = b ^ c
e = c ^ d

The final d and e will be:

d = b ^ c = a ^ (a ^ b) = a
e = c ^ d = (a ^ b) ^ (b ^ (a ^ b)) = b

It is a funny mathematical trick.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now