👉 문제 풀러가기 : https://school.programmers.co.kr/learn/courses/30/lessons/68935?language=javascript
자연수 n이 매개변수로 주어집니다. n을 3진법 상에서 앞뒤로 뒤집은 후, 이를 다시 10진법으로 표현한 수를 return 하도록 solution 함수를 완성해주세요.
입출력 예
n | result |
---|---|
45 | 7 |
125 | 229 |
function solution(n) {
let ternary = []
let result = 0
while(n > 0){
//나머지를 넣는다 [0,0,2,1] -> 이게 곧 10진수가 될 배열
ternary.push(n%3)
//소수점 없이 나누기 위해 Math.floor를 쓴다
//45 -> 15 -> 5 -> 1
n = Math.floor(n/3)
}
//거꾸로 넣어진 배열을 뒤집는다
//[1,2,0,0]
ternary.reverse()
for(let i = 0; i < ternary.length; i++){
//ternary[i] -> [1,2,0,0]
//Math.pow(3,i) -> 3을 i만큼 거듭제곱
//0 += 1 * 3^0(1)
//1 += 2 * 3^1(3)
//7 += 0 * 3^2(9)
//7 += 0 * 3^3(27)
result += ternary[i] * Math.pow(3, i)
}
//결과는 7!
return result
}
console.log(solution(45))