Learner Level

Implement the singleNumberUsingXor method that returns the number that appears once using XOR logic.

The input array nums contains integers where every value appears exactly twice except one value that appears only once.

Your task is to return the value that appears once.

For example, in [4,1,2,1,2], the duplicate values cancel out and the single value is 4.

Example 1
Input:
nums (int[]) = [4,1,2,1,2]
size (int) = 5
Return:
(int) 4
Example 2
Input:
nums (int[]) = [2,2,1]
size (int) = 3
Return:
(int) 1
Example 3
Input:
nums (int[]) = [1]
size (int) = 1
Return:
(int) 1

Use the XOR operator.

XOR has a useful property: x XOR x = 0 and x XOR 0 = x. So when all numbers are XORed together, pairs of equal numbers become zero and the only remaining value is the single number.

This solves the problem in one pass without using extra storage.

Pseudocode:

function singleNumberUsingXor(nums, size):
    result = 0
    for i from 0 to size - 1:
        result = result XOR nums[i]
    return result
Run your code to see the result.