자연수 n이 매개변수로 주어집니다. n을 3진법 상에서 앞뒤로 뒤집은 후, 이를 다시 10진법으로 표현한 수를 return 하도록 solution 함수를 완성해주세요.
n | result |
---|---|
45 | 7 |
125 | 229 |
입출력 예 #1
n (10진법) | n (3진법) | 앞뒤 반전(3진법) | 10진법으로 표현 |
---|---|---|---|
45 | 1200 | 0021 | 7 |
입출력 예 #2
n (10진법) | n (3진법) | 앞뒤 반전(3진법) | 10진법으로 표현 |
---|---|---|---|
125 | 11122 | 22111 | 229 |
public int solution(int n) {
int biggestPlaceValue = getBiggestPlaceValue(n); // 3진법 표현시 자릿수를 구한다.
String ternary = getTernary(biggestPlaceValue, n).toString(); // 자릿수를 이용해 3진법수를 구한다.
return getDecimal(ternary); // 3진법을 10진법으로 구한 수를 리턴
}
int getDecimal(String ternary) {
int idx = 0;
int decimal = 0;
for(char c : ternary.toCharArray()) { // 3진법을 뒤집어야 하므로 앞에서부터 가져온다.
int digit = Integer.parseInt(c + ""); // 3진법 자리의 수를 구함
decimal += (int)Math.pow(3, idx) * digit; // 10진법 처리를 위해 다시 3의 제곱수를 곱해준다.
idx += 1;
}
return decimal;
}
StringBuilder getTernary(int biggestPow, int n) {
StringBuilder stb = new StringBuilder();
for(int i = biggestPow; i >= 0; i--) { // 최대자리수부터 시작하여 감소
int num = n / (int)Math.pow(3, i); // 해당 자리의 들어갈 수를 구함
n = n - (int)Math.pow(3, i) * num; // 3진법 표현한만큼 n감소
stb.append(num);
}
return stb;
}
int getBiggestPlaceValue(int n) {
int biggestPlaceValue = 0;
for(int i = 0; i <= n; i++) { // 3^0=1, 3^1=3, 3^2=9, ...
if(n < Math.pow(3, i)) { // 3의 n제곱이 주어진 수보다 클때
biggestPlaceValue = i - 1; // n-1이 3진법 표현시 최대자릿수임
break;
}
}
return biggestPlaceValue;
}