Thursday, December 26, 2013

How many ways to swap to numbers without using third variable in java

Swapping of two numbers program is a frequently asking question in interviews.If we want to swap to two numbers ,We will use third variable. Let's see simple example below

public static void swappingNumbers(num1, num2) {
        var tempVariable = num1;
        num1 = num2;
        num2 = tempVariable;
}

Like above we will do. But we can do this program in three ways without using third variable.

1) In first way, we add first and second numbers then store result into first variable. After subtract second value from first result, store that result into second variable.At last, subtract second result from first result then store this result into first variable.For more clarification see  below program

    public static void swappingNumType1(num1, num2)
     {
          num1 = num1 + num2;
          num2 = num1 - num2;
          num1 = num1 - num2;
          System.out.println("num1 = "+num1+"  num2 = "+num2);
     }
    
2)
              In second way,we multiply first and second numbers then store this  result into first variable. After devide first result with second value,store second result into second variable. At last, divide first result with second result then store result into first variable. For more clarification see below program

     public static void swappingNumType1(num1, num2)
     {
          num1 = num1 * num2;
          num2 = num1 / num2;
          num1 = num1 / num2;
          System.out.println("num1 = "+num1+"  num2 = "+num2);
     }

3) In third way,we  will add two numbers by using ^(XOR) operator.

     public static void swappingNumType1(num1, num2)

     {
          num1 = num1 ^ num2;
          num2 = num1 ^ num2;
          num1 = num1 ^ num2;
          System.out.println("num1 = "+num1+"  num2 = "+num2);
     }

We will also swap two Strings without using third variable. It is possible by using subString() method of String API.

     public static void main(String[] args)
{
String a = "rrv";
String b = "techdiamod";
a = a+b;
b=a.substring(0,a.length()-b.length());
a=a.substring(b.length());
System.out.println("Swappng Strings are "+a+"    "+b);

    }


         
  

No comments:

Post a Comment