Last active
October 10, 2016 02:13
-
-
Save SH4DY/bb49b6999cc4587575d8 to your computer and use it in GitHub Desktop.
Swap two numbers in-place ==> without using a temp variable
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
//This method works only with integers | |
int a = 5; | |
int b = 7; | |
a = a-b; //diff. a = -2 | |
b = a+b; // b = 5 | |
a = b-a; // a = 7 | |
//This method relies on bit manipulation and does not depend on the number format | |
int c = 3; | |
int d = 4; | |
c = c^d; | |
d = c^d; | |
c = c^d; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment