Lockheed Martin interview question

Swap 2 integer values with only using two variables or less?

Interview Answers

Anonymous

Apr 4, 2013

I assume they mean you're given int a and int b and to swap their values without anything additional. int a = 5; int b = 10; b += a; // b = 10 + 5 = 15 a = b - a; // a = 15 - 5 = 10 b -= a; // b = 15 - 10 = 5

5

Anonymous

Jun 6, 2016

Swap 2 integer values with only using two variables or less? Answer: A=5 B=7 A=A^B 5^7 so A=2 B=A^B 2^7 so B=5 A=A^B A=7 2^5 from above