Created
October 12, 2017 06:44
-
-
Save unilecs/ebc04d9c6c3222ec19404eab28b11461 to your computer and use it in GitHub Desktop.
Get removed element in array
This file contains 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
function getRemovedElementInArray(arr, n) { | |
const totalSum = n*(n + 1) / 2; // формула арифмитческой прогрессии | |
let arrSum = 0; | |
arr.forEach(item => arrSum += item); | |
return totalSum - arrSum; | |
} | |
function getRemovedElementInArray2(arr, n) { | |
let arrXorSum = 0, totalXorSum = 0; | |
for (let i=1; i<=n; i++) { | |
totalXorSum ^=i; | |
} | |
arr.forEach(item => arrXorSum ^= item); | |
// свойство xor: если A xor B = C, то A = B xor C | |
return totalXorSum ^ arrXorSum; | |
} | |
const n = 10; | |
const arr = [1, 6, 7, 4, 5, 2, 3, 0, 10, 8]; | |
console.info(getRemovedElementInArray(arr, n)); | |
console.info(getRemovedElementInArray2(arr, n)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment