
n을 3진법으로 변환하기 위해서 n을 3으로 나눈 나머지를 배열에 저장하고 해당 배열을 뒤집으면 된다.
문제의 조건이 n을 3진법으로 변환하고 그 수를 뒤집은 후 10진법으로 표현하는 것이다.
3진법으로 변환한 수를 다시 뒤집기 때문에 n을 3진법으로 변환하는 과정에서 뒤집기 전의 배열을 구하면 된다.
구한 배열의 길이를 구하고 각 배열의 인덱스를 i라고 했을 때, 모든 인덱스의 3^((길이)-i+1)*배열[i]의 합을 구하면 된다.
import java.util.*;
class Solution {
public int solution(int n) {
int answer = 0;
List<Integer> ternary = toTernary(n);
int ternarySize = ternary.size();
int i = 1;
for (int num: ternary) {
answer += Math.pow(3, ternarySize-i)*num;
i ++;
}
return answer;
}
// 3진법으로 변환하는 합수
private List<Integer> toTernary (int n) {
List<Integer> ternaryList = new ArrayList<>();
while (n>0) {
ternaryList.add(n%3);
n /= 3;
}
return ternaryList;
}
}
