Find the stray number

Lee·2022년 6월 27일

Algorithm

목록 보기
31/92
post-thumbnail

❓ Find the stray number

Q. You are given an odd-length array of integers, in which all of them are the same, except for one single number.

Complete the method which accepts such an array, and returns that single different number.

The input array will always be valid! (odd-length >= 3)

Examples
[1, 1, 2] ==> 2
[17, 17, 3, 17, 17, 17, 17] ==> 3

✔ Solution

//#1 my solution
function stray(numbers) {
  return numbers.reduce((a, b) => a ^ b);
}


//#2 other solution
function stray(numbers) {
  var a = numbers.sort();
  
  if(a[0] != a[1]) {
    return a[0]
  } 
  return a[a.length-1]
}
profile
Lee

0개의 댓글