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 )
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
Post a Comment