Find the odd int
ํ์ ๋ฒ ๋ํ๋๋ ์ ์ ์ฐพ๊ธฐ
๋ฌธ์
์ฃผ์ด์ง ๋ฐฐ์ด์์, ํ์ ๋ฒ ๋ํ๋๋ ์ ์๋ฅผ ์ฐพ์์ฃผ์ธ์. ๋จ, ํ์ ๋ฒ ๋ํ๋๋ ์ ์๋ ํญ์ ํ๊ฐ๋ฟ์ ๋๋ค.
์๋ฅผ๋ค์ด, [1, 1, 1, 1, 10] ์์ 1์ 4๋ฒ ๋ํ๋๊ณ , 10์ 1๋ฒ ๋ํ๋๋ฏ๋ก, ํ์ ๋ฒ ๋ํ๋๋ ์ ์๋ 10 ์ ๋๋ค.
// @param { Array } n
function findOddInt (n) {
//happy coding!
}
๋ฌธ์ ์ดํด
์ ํํ ์ดํด๋ฅผ ์ํด ํ ์คํธ ์ธ์๋ฅผ ํ์ธํด ๋ณด์
expect(findOddInt([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5])).to.eql(5);
expect(findOddInt([9])).to.eql(9);
expect(findOddInt([1, 1, 1, 1, 1, 1, 3, 3, 3])).to.eql(3);
expect(findOddInt([5, 6, 4, 6, 5, 7, 1, 5, 7, 6, 5, 7, 6, 4, 1])).to.eql(7);
ํน๋ณํ ๋ ์๊ตฌํ๋ ์ฌํญ์ ์๋ค. ๋ฐฐ์ด์์ ๋ค์ด์ค๋ ์ซ์์ค ๋ฐ๋ณต ํ์๊ฐ ์ ํํ ํ์์ธ ์์๋ฅผ ์ฐพ๋๋ค.
ํด๊ฒฐ ๋ฐฉ๋ฒ
์์๋ง๋ค์ ๋ค์ด๊ฐ ํ์๋ฅผ ์ฒดํฌํ๋๋ฐ ์ด์ ์ ์ฒดํฌํ ์์์ธ์ง ์ ํํ๊ฒ ํ๋จํ๋ค.
์ฒดํฌํ ์์๋ ๋ฐ๋ก ๋ฐฐ์ด์ ๋ด๋๋ค.
ํ์ ๊ฐ์์ธ์ง ์ฒดํฌ
๋ง๋ค๋ฉด return
์ฝ๋ ๊ตฌํ
function findOddInt (n) {
let newN = [];
let overlap = false;
let count = 1;
let answer;
n.forEach((num, idx) => {
// ์ด์ ์ฒดํฌํ ์ซ์์ธ์ง ์ฒดํฌํ๋ค.
for (let newNum of newN) {
if (num === newNum) {
overlap = true;
break;
}
overlap = false;
}
// ์ด์ ์ ์ฒดํฌํ ์ซ์๊ฐ ์๋๋ผ๋ฉด,
if (!overlap || idx === 0) {
newN.push(num);
// num ์ index ๋ค์์๋ฆฌ๋ถํฐ ๊ฐ์๋ฅผ ์ฒดํฌ
for (let checkNum = (idx + 1); checkNum < n.length; checkNum++) {
if (n[checkNum] === num) {
count++;
}
}
// ํ์ ๊ฐ์์ธ์ง ์ฒดํฌ
if (count % 2 === 1) {
answer = num;
}
}
//count ๋ฆฌ์
count = 1;
});
return answer;
}
๊ฒฐ๊ณผ ๋ถ์
๋๋คํ ์คํธ ํต๊ณผ
harms280, ChingChangChong, oscar6654, aaronbulnes, ghismovd, Jaykobee's Codewars Solution
function findOddInt(A) {
var obj = {};
A.forEach(function(el){
obj[el] ? obj[el]++ : obj[el] = 1;
});
for(prop in obj) {
if(obj[prop] % 2 !== 0) return Number(prop);
}
์๋ก์ด ๋ฐฐ์ด์ ๋ง๋ค์ด์ findOddInt ํจ์์ ์ธ์ ๋ฐฐ์ด์์ ์์๊ฐ key๊ฐ ๋๊ณ ๊ทธ key์ ๊ฐ์๊ฐ value๊ฐ ๋๋ค. ์ ๋ถ๋ค ๋ด๊ฒ ๋๋ฉด value๊ฐ์ด ํ์์ธ key๋ฅผ ๋ฆฌํดํด ์ค๋ค.
Unnamed, classic016, Fantom1991, TroyMaeder, saiful_coder, dany.dlinker's Codewars Solution
const findOdd = (xs) => xs.reduce((a, b) => a ^ b);
์ด๊ฑฐ์จ.. (https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_XOR) ๊ดํ solution์ธ๋ฐ ์์ง ์ ๋ชจ๋ฅด๊ฒ ๋ค.
Last updated
Was this helpful?