Skip to content

Instantly share code, notes, and snippets.

@shailrshah
Last active November 6, 2017 17:27
Show Gist options
  • Select an option

  • Save shailrshah/6752ad6fd7fb34edefaa5061b6dd03e5 to your computer and use it in GitHub Desktop.

Select an option

Save shailrshah/6752ad6fd7fb34edefaa5061b6dd03e5 to your computer and use it in GitHub Desktop.
Swap two numbers A and B, without using a temporary variable.
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