Last active
October 26, 2015 15:56
-
-
Save davepkennedy/b25456bf680bd640e53e to your computer and use it in GitHub Desktop.
Swap two numbers without an intermediate variable. Still takes as many statement as with one though…
This file contains hidden or 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
| Swap two numbers without an intermediate variable. Still takes as many statement as with one though… | |
| Consider a = 5, b = 10 | |
| a = b0101 | |
| b = b1010 | |
| a = a ^ b -> b0101 ^ b1010 -> a = b1111 (15) | |
| b = a ^ b -> b1111 ^ b1010 -> b = b0101 (5) | |
| a = a ^ b -> b1111 ^ b0101 -> a = b1010 (10) | |
| a = b1010 = 10 | |
| b = b0101 = 5 | |
| Values are now swapped. Easy. |
This file contains hidden or 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
| #include <stdio.h> | |
| #define SWAP(a,b) {a = a^b; b = a^b; a = a^b;} | |
| int main(int argc, const char * argv[]) { | |
| // insert code here... | |
| int x = 3; | |
| int y = 298; | |
| printf("x = %d, y = %d\n", x, y); | |
| SWAP(x,y); | |
| printf("x = %d, y = %d\n", x, y); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment