Last active
November 6, 2017 17:27
-
-
Save shailrshah/6752ad6fd7fb34edefaa5061b6dd03e5 to your computer and use it in GitHub Desktop.
Swap two numbers A and B, without using a temporary 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
| public static void swap(int x, int y) { | |
| if(x == y) return; | |
| x = x ^ y; // x = A ^ B, y = B | |
| y = x ^ y; // x = A ^ B, y = A ^ (B ^ B) = A ^ 0 = A | |
| x = x ^ y; // y = A, x = A ^ B ^ A = B ^ (A ^ A) = B ^ 0 = B | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment