코딩 테스트/프로그래머스 level1
3진법 뒤집기
fullfish
2022. 9. 8. 01:32

코드
function solution(n) {
let origin = 1;
let result = 0;
let resultArr = [];
while (n >= origin) {
origin *= 3;
}
while (n > 0) {
origin /= 3;
resultArr.push(parseInt(n / origin));
n = n % origin;
}
for (let i = 0; i < resultArr.length; i++) {
result += Math.pow(3, i) * resultArr[i];
}
return result;
}
다른 방법
const solution2 = (n) => {
return parseInt([...n.toString(3)].reverse().join(""), 3);
};
toStirng 자체에 n진법으로 변환하는 기능이 있다
마찬가지로 parseInt에도 있다
다른 방법
function solution3(n) {
const answer = [];
while (n !== 0) {
answer.unshift(n % 3);
n = Math.floor(n / 3);
}
return answer.reduce((acc, v, i) => acc + v * Math.pow(3, i), 0);
}