Given two numbers a and b, swap their values without using a temporary variable.
^) operator, leveraging its properties:
x ^ x = 0).x ^ 0 = x).a = a ^ bb = a ^ b (substitutes to (a ^ b) ^ b = a)a = a ^ b (substitutes to (a ^ b) ^ a = b)a = 5 (binary: 101), b = 6 (binary: 110)a = 5 ^ 6 = 3 (binary: 011)b = 3 ^ 6 = 5 (binary: 101)a = 3 ^ 5 = 6 (binary: 110)a = 6, b = 5public 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);
}
}
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.
i positions (1 << i), which sets only the i-th bit to 1.