Monday, June 9, 2014

Swap two numbers

Solutions:
1) Using temporary variable / Using extra space
2) Without using temporary variable / Without using extra space
     a) Using arithmetic operators
     b) Using bitwise operator

Solution 1: Using temporary variable
//SwapUsingExtraVariable.java
public class SwapUsingExtraVariable {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        System.out.println("Values before swapping");
        System.out.println("a= " +a + " b= "+b);
        int temp = a;
        a = b;
        b = temp;
        System.out.println("Values after swapping");
        System.out.println("a= " +a + " b= "+b);
    }
}
// Output:
//Values before swapping
//a= 10 b= 20
//Values after swapping
//a= 20 b= 10
Solution 2 a: Using arithmetic operators
//SwapUsingArthematic.java
public class SwapUsingArthematic {
	public static void main(String[] args) {
		int a = 10;
		int b = 20;
		
		System.out.println("Values before swapping");
		System.out.println("a= " +a + " b= "+b);
		
		a = a + b;
		b = a - b;
		a = a - b;
                
                // a = a * b;
                // b = a / b;
                // a = a / b;

		System.out.println("Values after swapping");
		System.out.println("a= " +a + " b= "+b);
	}
}
// Output:
//Values before swapping
//a= 10 b= 20
//Values after swapping
//a= 20 b= 10
   
We can use "*" & "/" operators also instead of "+" & "-". Check the above program lines 14, 15 and 16 for the reference. But problem with "/" operator is it gives java.lang.ArithmeticException: / by zero Exception for "b" value is zero.

Solution 2 b: Using bitwise operator
//SwapUsingBitWiseOperator.java
public class SwapUsingBitWiseOperator {

	public static void main(String[] args) {
		int a = 10;
		int b = 20;
		
		System.out.println("Values before swapping");
		System.out.println("a= " +a + " b= "+b);
		
		a = a ^ b;
		b = a ^ b;
		a = a ^ b;

		System.out.println("Values after swapping");
		System.out.println("a= " +a + " b= "+b);
	}

}
// Output:
//Values before swapping
//a= 10 b= 20
//Values after swapping
//a= 20 b= 10

No comments:

Post a Comment