Skip to main content

XOR Operator

Swap Two Numbers

1 min read

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.

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

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

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

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++

#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

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).

Reading Progress