Skip to content

Instantly share code, notes, and snippets.

@unilecs
Created October 7, 2017 19:59
Show Gist options
  • Save unilecs/25803cf8c0b2587c2de8ccb8fea451ad to your computer and use it in GitHub Desktop.
Save unilecs/25803cf8c0b2587c2de8ccb8fea451ad to your computer and use it in GitHub Desktop.
Get number w/o pair in the array of numbers
function getUniqueNumberInArray(arr) {
if (!arr || !arr.length) {
return null;
}
let result = arr[0];
for (let i=1; i<arr.length; i++) {
result ^= arr[i]; // XOR each element in array
}
return result;
}
const arr = [ 0, 4, -1, 5, -1, 4, 0 ];
console.info(getUniqueNumberInArray(arr));
@Borzilov
Copy link

Borzilov commented Oct 9, 2017

Maybe for-loop could be changed to:
arr.reduce( (result, element) => result ^ element )

@unilecs
Copy link
Author

unilecs commented Oct 11, 2017

Borzilov, good point.
But I try don't any cool functions from the "box" of language. Here it will be syntactic sugar and will not affect the algorithm itself.
The decision should be understood even by those who do not know the language

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment