Hyebin‘s blog

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).

 

 

 

<Code>

function findOdd(A) {
  let count = 0;
  let result = 0;

  arr = A.sort(); //배열 정렬
  //console.log(arr); 
  for (let i = 0; i < arr.length; i++) { 
    if (arr[i] === arr[i + 1]) {// arr[i]와 arr[i+1]이 같을 때 까지 count ++
      count++;
    } else {
      count++; 

      if (count % 2 !== 0) { //만약 다르면 누적된 count값이 2의 배수가 아ㅣㄴ면 
        result = arr[i]; //그 값을 return
        break;
      }
    }
  }
  //console.log(result);
  return result;
}

findOdd([1, 1, 2, -2, 5, 2, 4, 4, -1, -2, 5]);

 

'Algorithm > Codewars' 카테고리의 다른 글

[Codewars/JS] Convert string to camel case  (0) 2022.01.30
[Codewars/JS] Disemvowel Trolls  (0) 2022.01.21
[Codewars/JS] Vowel Count  (0) 2022.01.18
[Codewars/JS] Moving Zeros To The End  (0) 2022.01.14
[Codewars/JS] RGB To Hex Conversion  (0) 2022.01.13
profile

Hyebin‘s blog

@hyebin Lee

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!

검색 태그