The task is to implement a function that quickly targets an integer that appears once, given an array of integers that appear twice.
The boilerplate code
function findSingle(arr) {
// your code here
}
The single integer can be quickly targeted using the XOR trick (^). Using the example
a ^ a = 0
Two numbers that are the same cancel out. So, using the XOR method, all numbers in pairs will cancel out.
for(let num of arr) {
result ^= num
}
Then the remaining integer is returned. The final code:
function findSingle(arr) {
// your code here
let result = 0;
for(let num of arr) {
result ^= num;
}
return result;
}
That's all folks!
Top comments (0)