Saturday, February 28, 2015

Swap numbers without temporary variables


Write a function to swap a number in place without temporary variables.
using XOR.  a = 3 (11), b = 5 (101). a = a ^ b = 110 b = a ^ b  =  3(11), because we flip the bits back. a = a ^ b = 5 (101)


public static void swap(int a, int b){
  a = a ^ b;
  b = a ^ b;
  a = a ^ b;
  System.out.println("a: " + a);
  System.out.println("b: " + b);
 }

No comments:

Post a Comment