Write a program to swap the values of two integers without using a third variable. The program should accept two integers as input and output their values after swapping.
Input: 5 10
Output: 10 5
Input: -3 7
Output: 7 -3
Input: 0 0
Output: 0 0
We can swap two numbers without a third variable using the XOR bitwise operation. XOR has properties that allow us to reverse the operation: if we XOR a number with another twice, we get the original number back.
a = a ^ b – Now a holds the combined bits of both.b = a ^ b – Retrieves original a and stores it in b.a = a ^ b – Retrieves original b and stores it in a.#include <iostream>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
a = a ^ b;
b = a ^ b;
a = a ^ b;
cout << a << " " << b;
return 0;
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
a = a ^ b;
b = a ^ b;
a = a ^ b;
System.out.println(a + " " + b);
}
}
a, b = map(int, input().split())
a = a ^ b
b = a ^ b
a = a ^ b
print(a, b)
const [a, b] = require('fs').readFileSync(0, 'utf8').trim().split(/\s+/).map(Number);
a = a ^ b;
b = a ^ b;
a = a ^ b;
console.log(a, b);
Time Complexity: O(1), because we perform a fixed number of arithmetic/XOR operations independent of input size.
Space Complexity: O(1), as we only use two integer variables without any additional data structures.
Your notes are automatically saved in your browser's local storage and will persist across sessions on this device.