SWAPPING OF TWO NUMBER WITHOUT USING THIRD VARIABLE (XOR Bitwise operator)

 SWAPPING OF TWO NUMBER WITHOUT USING THIRD VARIABLE  (XOR Bitwise operator)

 with the use of XOR bitwise operator we can swap two number without using third variable
XOR(^) : help to inverse the binary or decimal number 

      

ALGORITHM 
  • Take two variable a and b
  • assign value of a and b  (as we assign a=10 and b=15)
  • then a = a^b ( value of a will change to 5 )
          because  a  =10 =1 0 1 0  |   only one bit should be 1 so 
                         b =15 = 1 1 1 1  |   answer will be 1 or true
                         a ^ b  =  0 1 0 1    .i.e. 5
  • now b = a^b (here a = 5 and b = 15) then, value of b =10
        because  a  =5   =  0 1 0 1     
                        b =15 =  1 1 1 1 
                        a ^ b  =   1 0 1 0    
  • a = a^b ( value of a will swap to 15)
        because  a  =5   =  0 1 0 1     
                        b =10 =  1 0 1 0
                        a ^ b  =   1 1 1 1   .i.e. 15  
  • result a =15 and b=10

Java code   

package com.company;

import java.util.Scanner;

public class Main {

public static void main(String[] args) {
int a=10,b=15;
System.out.println("Before swapping value of a : 10");
System.out.println("Before swapping value of b : 15");
a=a^b;
b=a^b;
a=a^b;
System.out.println("After swapping a : "+a);
System.out.println("After swapping b : "+b);

}
}
output:-
Before swapping value of a : 10
Before swapping value of b : 15
After swapping a : 15
After swapping b : 10

Process finished with exit code 0

Comments

Popular posts from this blog

the distance between two cities (in km is input through the keyboard. write a program to convert and print this distance in meter ,feet inches and centimeter.

CREATE UNIT CONVERTER APP

write a program to check whether a triangle is valid or not, when the threeangles of the triangle are entered through the keyboard. A triangle is valid if the sumof all the three angles is equal to 180 degrees