Last active
October 15, 2021 03:39
-
-
Save mmyoji/54dfb32753ed6d4e30d1094399fac93a to your computer and use it in GitHub Desktop.
XOR use cases
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://florian.github.io/xor-trick/ | |
function swap(a: number, b: number): [number, number] { | |
a ^= b; | |
b ^= a; | |
a ^= b; | |
return [a, b]; | |
} | |
/** | |
* @param {number[]} arr :: an array of numbers which contains number 1 ~ `n`, but lacks one of them. | |
* @param {number} n :: the supposed max number of `arr` | |
* @returns {number} the lacked number | |
* @example findUnknownNumber([1, 2, 3, 5], 5) //=> 4 | |
* @note This function is also used to find _duplicated_ number of an array. | |
* const findDuplicatedNumber = findUnknownNumber; | |
* findDuplicatedNumber([1, 2, 2, 3, 4, 5], 5) //=> 2 | |
*/ | |
function findUnknownNumber(arr: number[], n: number): number { | |
let result = 0; | |
for (let i = 1; i < n + 1; i++) { | |
result ^= i; | |
} | |
for (const value of arr) { | |
result ^= value; | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment