Created
May 22, 2012 21:57
-
-
Save campo/2771897 to your computer and use it in GitHub Desktop.
Templess Swap from Etsy Interview
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Given two variables with integer values assumed positive, swap the values without using | |
// a temp variable | |
function templessSwap($a, $b){ | |
print("Swapping the values without a temp variable...\n"); | |
print("The initial values are:\nA: $a\nB: $b\n"); | |
$a = $a ^ $b; | |
$b = $a ^ $b; | |
$a = $a ^ $b; | |
print("The values after the swap are:\nA: $a\nB: $b\n\n"); | |
} | |
// Just a few test calls to the swap method here | |
templessSwap(1,2); | |
templessSwap(2,1); | |
templessSwap(-1,-1); | |
templessSwap(3,7); | |
templessSwap(1000, 10358); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment