algorithm/codewars

[6kyu] Compare powers

안준범 2018. 6. 15. 20:22

문제설명


You certainly can tell which is the larger number between 210 and 215.

But what about, say, 210 and 310? You know this one too.

Things tend to get a bit more complicated with both different bases and exponents: which is larger between 39 and 56?

Well, by now you have surely guessed that you have to build a function to compare powers, returning -1 if the first member is larger, 0 if they are equal, 1 otherwise; powers to compare will be provided in the [base, exponent] format:

comparePowers([2,10],[2,15])===1
comparePowers([2,10],[3,10])===1
comparePowers([2,10],[2,10])===0
comparePowers([3,9],[5,6])===-1
comparePowers([7,7],[5,8])===-1

Only positive integers will be tested, incluing bigger numbers - you are warned now, so be diligent try to implement an efficient solution not to drain too much on CW resources ;)




나의 풀이

const comparePowers = (n1, n2) => { const val1 = n1[1] * Math.log(n1[0]); const val2 = n2[1] * Math.log(n2[0]); return (val1 > val2) ? -1 : (val1 === val2 ? 0 : 1); 

}




다른사람의 풀이

function comparePowers([b1, e1], [b2, e2]) { <--------- ES6 비구조화 할당 let d = Math.log(b2) * e2 - Math.log(b1) * e1; return (d > 0) - (d < 0); 
}





느낀점

고등학교 수학 로그가 생각났다. 로그의 성질을 조금만 알면 금방 풀 수 있는 문제 같다.
모든사람의 풀이가 똑같다 ㅋㅋㅋ. 다만 내가 ES6 문법인 비구조화 할당을 썼다면 더 좋았지 싶다.