Java program to swap two numbers using bitwise operator

Configurare noua (How To)

Situatie

We will be creating a Java program to swap two numbers using bitwise operator (^).

Solutie

Pasi de urmat

import java.util.Scanner;
public class SwapTwoNumbersExample
{
public static void main(String args[])
{
int a, b;
Scanner scanner = new Scanner(System.in);
System.out.print(“Enter the first number: “);
a = scanner.nextInt();
System.out.print(“Enter the second number: “);
b = scanner.nextInt();
System.out.println(“Before swapping:”);
System.out.println(“a = ” +a +”, b = ” +b);
a = a ^ b;
b = a ^ b;
a = a ^ b;
System.out.println(“After swapping:”);
System.out.print(“a = ” +a +”, b = ” +b);
}
}

Output:

Enter the first number: 5
Enter the second number: 9
Before swapping:
a = 5, b = 9
After swapping:
a = 9, b = 5

Tip solutie

Permanent

Voteaza

(3 din 6 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?