1. Swapping Two Numbers Using XOR

Problem Statement

Given two numbers a and b, swap their values without using a temporary variable.

Solution Explanation

Example

Java Code

public class SwapNumbers {
    public static void main(String[] args) {
        int a = 5;
        int b = 6;
        System.out.println("Before swap: a = " + a + ", b = " + b);
        a = a ^ b;
        b = a ^ b;
        a = a ^ b;
        System.out.println("After swap: a = " + a + ", b = " + b);
    }
}


2. Check if the i-th Bit is Set

Problem Statement

Given a number n and an index i (counting from the right, starting at 0), determine if the i-th bit is set (1) in n’s binary representation.

Solution Explanation