Find the Element That Appears Once
Problem
Every value in the array appears exactly twice except for one. Find the loner. Use the XOR identity x ⊕ x = 0: XOR-ing every element together cancels each duplicated pair, and the lone value remains.
Input
nums = [4, 2, 9, 4, 2]Output
94 ⊕ 2 ⊕ 9 ⊕ 4 ⊕ 2 = 9.
def single_number(nums):
acc = 0
for x in nums:
acc ^= x
return acc
function singleNumber(nums) {
let acc = 0;
for (const x of nums) acc ^= x;
return acc;
}
class Solution {
public int singleNumber(int[] nums) {
int acc = 0;
for (int x : nums) acc ^= x;
return acc;
}
}
int singleNumber(vector<int>& nums) {
int acc = 0;
for (int x : nums) acc ^= x;
return acc;
}