interview-preparation / what-we-do

0 stars 8 forks source link

[Moderate] interview questions #1 #128

Closed rygh4775 closed 5 years ago

rygh4775 commented 5 years ago

Number Swapper: Write a function to swap a number in place (that is, without temporary variables).

RoyMoon commented 5 years ago

Solution 1 int a = 2; // a : 2 int b = 4; // b : 4

A = a + b; // a : 6 | b : 4
B = A - b; // a : 6 | b : 2 B = (a + b) -b  즉 a A = A - B; // a : 4 | b : 2 A = (a +b) - ((a+b) -b) 즉 b

Solution 2 int a = 2; // a : 2 int b = 4; // b : 4

A = ab; //now a is 8 and b is 4 B = A/b; //now a is 8 but b is 2 B = (ab) / b = a A = A/B; //now a is 4 and b is 2 A = (a*b)/a = b

Solution 3 int a = 2; int b = 4;

A = a ^ b B = A ^ b = a ^(b^b) = a^0 = a A = A ^ B = a^b ^ a^ b ^ b = (a^a)^(b^b) ^b = 0^0^ b= b