fork download
  1. import java.util.Scanner;
  2.  
  3. class SumXorDifference {
  4.  
  5. public static int sumXor(int N, int[] A) {
  6. int oddSum = 0;
  7. int evenXor = 0;
  8.  
  9. // Loop through the array
  10. for (int i = 0; i < N; i++) {
  11. if (i % 2 == 0) {
  12. // Even index - apply XOR
  13. evenXor ^= A[i];
  14. } else {
  15. // Odd index - apply sum
  16. oddSum += A[i];
  17. }
  18. }
  19.  
  20. // Return the difference
  21. return oddSum - evenXor;
  22. }
  23.  
  24. public static void main(String[] args) {
  25. // Create a scanner object to take input from the user
  26. Scanner scanner = new Scanner(System.in);
  27.  
  28. // Input for array length
  29. System.out.print("Enter the length of the array (N): ");
  30. int N = scanner.nextInt();
  31.  
  32. // Initialize the array
  33. int[] A = new int[N];
  34.  
  35. // Input for array elements
  36. System.out.println("Enter the elements of the array: ");
  37. for (int i = 0; i < N; i++) {
  38. A[i] = scanner.nextInt();
  39. }
  40.  
  41. // Call the sumXor method and store the result
  42. int result = sumXor(N, A);
  43.  
  44. // Output the result
  45. System.out.println("The result is: " + result);
  46.  
  47. // Close the scanner object
  48. scanner.close();
  49. }
  50. }
  51.  
Success #stdin #stdout 0.17s 59028KB
stdin
6
2 3 4 5 11 8
stdout
Enter the length of the array (N): Enter the elements of the array: 
The result is: 3