본문 바로가기
코테연습

19.Find the odd int

by hxunz 2022. 3. 29.

Given an array of integers, find the one that appears an odd number of times.

There will always be only one integer that appears an odd number of times.

Examples

[7] should return 7, because it occurs 1 time (which is odd).
[0] should return 0, because it occurs 1 time (which is odd).
[1,1,2] should return 2, because it occurs 1 time (which is odd).
[0,1,0,1,0] should return 0, because it occurs 3 times (which is odd).
[1,2,2,3,3,3,4,3,3,3,2,2,1] should return 4, because it appears 1 time (which is odd).

 

function findOdd(A) {
  const number = A.reduce(function (allNum, num) {
    if (num in allNum) {
      allNum[num]++;
    } else {
      allNum[num] = 1;
    }
    return allNum;
  }, {});
  
  let orderNum = '';
  
  for (i=0; i < Object.values(number).length; i++) {
    if (Object.values(number)[i] % 2 === 1) {
      orderNum += i;
    }
  }
  
  for (i=0; i < Object.keys(number).length; i++) {
    return parseInt(Object.keys(number)[orderNum]);
  }
}

 

우선, 주어진 배열에서 중복된 숫자가 있는지 확인하기 위해서 reduce를 사용했다.

mdn 공식 문서를 보니까 이렇게 예시까지 나와있어서 따라서 해봤다.

이렇게 해서 배열 내 숫자마다 몇개씩 사용되었는지 구할 수 있었고 이를 객체로 나타냈다. 

 

그 다음에 이 객체의 value가 홀수인지 아닌지 확인하기 위해서 for문, Object.values() 를 사용했다.

Object.values()를 사용하면 value들이 배열로 나타나기 때문에 for문을 사용할 수 있었다. 

 

몇번째에서 홀수 value를 갖는지 알기 위해서 따로 orderNum을 선언해줬었다. 

 

그 다음에는 홀수 value를 갖는 key를 찾기 위해서 for문, Object.keys()를 사용했다.

위에서 구한 orderNum을 이용했다. 

for (i=0; i < Object.keys(number).length; i++) {
return parseInt(Object.keys(number)[orderNum]);
}

그냥 리턴하면 string으로 나오기 때문에 테스트 통과가 안된다.

그래서 parseInt()를 사용해서 string to number를 해줬다.

 

 

 

 

제출하고 봤더니 추천 제일 많이 받은 사람은 이걸 한줄로 끝냈더라,,,, ㅋ 

function findOdd(A) {
  const findOdd = (xs) => xs.reduce((a, b) => a ^ b);
  return findOdd(A);
}

'코테연습' 카테고리의 다른 글

21.Sum of Digits / Digital Root  (0) 2022.03.31
20.Stop gninnipS My sdroW!  (0) 2022.03.30
18.Multiples of 3 or 5  (0) 2022.03.29
17.Find the next perfect square!  (0) 2022.03.27
16.Growth of a Population  (0) 2022.03.26

댓글