Swap two variables without using a temporary or additional values
This is normal programming practice.
Solution:
public class SwapVariables{
public static void main(String[] args) {
int a = 2,b = 4;
System.out.println("Before Swap ");
System.out.println("Value of A: "+a);
System.out.println("Value of B: "+b);
a = a ^ b;
b = a ^ b;
a = a ^ b;
System.out.println("After Swap ");
System.out.println("Value of A: "+a);
System.out.println("Value of B: "+b);
}
}
Solution:
public class SwapVariables{
public static void main(String[] args) {
int a = 2,b = 4;
System.out.println("Before Swap ");
System.out.println("Value of A: "+a);
System.out.println("Value of B: "+b);
a = a ^ b;
b = a ^ b;
a = a ^ b;
System.out.println("After Swap ");
System.out.println("Value of A: "+a);
System.out.println("Value of B: "+b);
}
}
Comments