> ## Content Index
> Fetch the complete content index at: https://www.javahandbook.com/llms.txt
> Use this file to discover other available public pages before exploring further.

# Swap Two Numbers
- URL: https://www.javahandbook.com/bitmask/swap-two-numbers/
- Published: 2024-06-16T07:50:46.000Z
- Updated: 2024-06-17T03:42:57.000Z
- Author: Gopi Gorantala
- Tags: XOR Operator, #bitmask, #docs

In this lesson, we use the XOR operator to swap the values of two inputs.

## Introduction

In this question, input two numbers and swap them without using the swapping logic.

## Problem statement

We need to write a program to swap two numbers.

```json
Input: a = 10, b = 121 

Output: a = 121, b = 10
```

## Solution

We can make use of XOR to swap two values. You will find the solution below:

### Java

```java
class SwapTwoNumbers {
    public static void main(String[] args) {

        int a = 10, b = 121;
        a = a ^ b;
        b = b ^ a;
        a = a ^ b;

        System.out.println("Finally, after swapping; a = " + a + " , b = " + b);
    }
}
```

### Python

```py
def swap_nums(a,b):
    a=a^b
    b=b^a
    a=a^b
    print("Finally, after swapping a =", a, ",b =", b)

a=10
b=121
swap_nums(a,b)

```

### JavaScript

```js
const SwapTwoNumbers = (a, b) => {
    a = a ^ b;
    b = b ^ a;
    a = a ^ b;

    console.log (`Finally, after swapping; a = ${a} , b = ${b}`)
}

const a = 10;
const b = 121;

SwapTwoNumbers (a, b);

```

### C++

```cpp
#include <iostream>

using namespace std;

int main() {
    int a = 10, b = 121;
    a = a ^ b;
    b = b ^ a;
    a = a ^ b;
    cout << "Finally, after swapping; a= " << a << " , b = " << b;
    return 0;
}
```

### TypeScript

```ts
export const SwapTwoNumbers = (a: number, b: number): void => {
    a = a ^ b;
    b = b ^ a;
    a = a ^ b;

    console.log(`Finally, after swapping; a = ${a} , b = ${b}`)
}

const a: number = 10;
const b: number = 121;

SwapTwoNumbers(a, b);
```

## Complexity analysis

**Time Complexity:** We are not running a loop or scaling the inputs. The inputs never change. So the operation takes a single unit of time, which is `*O*(1)`.

**Space Complexity:** We didn’t create an extra memory for this. So, the space complexity is `*O*(1)`.