3진법 뒤집기
자연수 n이 매개변수로 주어집니다. n을 3진법 상에서 앞뒤로 뒤집은 후, 이를 다시 10진법으로 표현한 수를 return 하도록 solution 함수를 완성해주세요.
10진법 → 3진법 → 앞뒤반전 → 10진법
public int solution(int n) {
int answer = 0;
int a = n;
List<Integer> list = new ArrayList<>();
while(a>=3) {
int b = a%3;
a =a/3;
list.add(b);
}
list.add(a);
//Integer.parseInt(숫자, 진법)을 사용하면 더 간단
for(int i=0; i< list.size(); i++) {
answer+= Math.pow(3,Math.abs(i-(list.size()-1))) * list.get(i);
}
return answer;
}
Plain Text
복사
[다른 사람 풀이]
class Solution {
public int solution(int n) {
String a = "";
while(n > 0){
a = (n % 3) + a;
n /= 3;
}
a = new StringBuilder(a).reverse().toString();
return Integer.parseInt(a,3);
}
JavaScript
복사
[깨달은 점]
Integer.paseInt로 n진법 변환 가능