I want to share 1 question which is asked most of the time in interviews and I wasn't able to e answer that question, but finally I found the answer:
How to Swap 2 variable value without using 3rd variable??
Code: Swap two variables value without using third variable php $a = 15; $b = 276; echo "\nBefore swapping: ". $a . ',' . $b; list($a, $b) = array($b, $a); echo "\nAfter swapping: ".
Given two variables, x, and y, swap two variables without using a third variable. The idea is to get a sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from the sum.
This method will work for any variable type:
$a = 5;
$b = 6;
list($a, $b) = array($b, $a);
print $a . ',' . $b;
Output:
6,5
Another simple way (which only works for numbers, not strings/arrays/etc) is
$a = $a + $b; // 5 + 6 = 11
$b = $a - $b; // 11 - 6 = 5
$a = $a - $b; // 11 - 5 = 6
print $a . ',' . $b;
Output:
6,5
Surely you want the XOR swap algorithm ? At least for numeric variables.
Conventional swapping requires the use of a temporary storage variable. Using the XOR swap algorithm, however, no temporary storage is needed. The algorithm is as follows:
X := X XOR Y
Y := X XOR Y
X := X XOR Y
Although I've never seen it used in real scenarios (beyond assembler work)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With