Java Online Compiler
Example: FindMissingNumberXOR in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// FindMissingNumberXOR import java.util.Arrays; public class Main { public static void main(String[] args) { int[] arr1 = {3, 1, 5, 2}; // Missing 4 System.out.println("Array: " + Arrays.toString(arr1) + ", Missing number: " + findMissingNumberXOR(arr1)); int[] arr2 = {1, 2, 3, 5, 6}; // Missing 4 System.out.println("Array: " + Arrays.toString(arr2) + ", Missing number: " + findMissingNumberXOR(arr2)); int[] arr3 = {2, 3, 4, 5}; // Missing 1 System.out.println("Array: " + Arrays.toString(arr3) + ", Missing number: " + findMissingNumberXOR(arr3)); } /** * Finds the missing number in an array using the XOR method. * Assumes numbers from 1 to n+1, with one number missing. * * @param arr The input array of distinct integers. * @return The missing integer. */ public static int findMissingNumberXOR(int[] arr) { // Step 1: Initialize XOR result. int xorResult = 0; // Step 2: XOR all numbers from 1 to (n+1) (the expected range). // 'n' is arr.length, so the max number in the full sequence is n + 1. int nPlus1 = arr.length + 1; for (int i = 1; i <= nPlus1; i++) { xorResult ^= i; } // Step 3: XOR all numbers present in the array with the current xorResult. for (int num : arr) { xorResult ^= num; } // Step 4: The final xorResult is the missing number. // All present numbers and their counterparts from the full sequence cancel each other out (X ^ X = 0). // Only the missing number remains. return xorResult; } }
Output
Clear
ADVERTISEMENTS