Slider

Swap Two Numbers in Java.

In this approach, we use a third variable to swap the values of the two variables. Using the XOR operator. Using arithmetic operations

We can swap two numbers in Java with multiple approaches and in this article, we are going to discuss all those approaches in detail with code.


Approach 1: Using a third variable

In this approach, we use a third variable to swap the values of the two variables.


Java Example Code:

int a = 10;
int b = 20;
int temp;

temp = a;
a = b;
b = temp;

System.out.println("a = " + a); // Output: a = 20
System.out.println("b = " + b); // Output: b = 10

Approach 2: Using arithmetic operations

In this approach, we can use arithmetic operations like addition, subtraction, multiplication, and division to swap the values of the two variables.

Java Example Code:
int a = 10;
int b = 20;

a = a + b; // a = 30
b = a - b; // b = 10
a = a - b; // a = 20

System.out.println("a = " + a); // Output: a = 20
System.out.println("b = " + b); // Output: b = 10

Approach 3: Using the XOR operator

In this approach, we can use the XOR (^) operator to swap the values of the two variables.

Java Example Code:

int a = 10;
int b = 20;

a = a ^ b; // a = 30 (11110)
b = a ^ b; // b = 10 (01010)
a = a ^ b; // a = 20 (10100)

System.out.println("a = " + a); // Output: a = 20
System.out.println("b = " + b); // Output: b = 10
All these approaches have the same time complexity of O(1) as they take constant time to swap the values of two variables. (alert-success)
0

No comments

Post a Comment

both, mystorymag

DON'T MISS

Tech News
© all rights reserved
made with by AlgoLesson
Table of Contents