1. 내 풀이
https://school.programmers.co.kr/learn/courses/30/lessons/68935
class Solution {
public int solution(int n) {
int answer = 0;
// 10진법을 3진법으로 만들기
/*
45일 때, 45%3 = 0
15 % 3 = 0
5 % 3 = 2
1 % 3 = 1
toThird = 0021
*/
String toThird = "";
while(n != 0) {
toThird += (n % 3);
n /= 3;
}
// 3진법을 10진법으로 만들기
/*
toThird = 0021
1 * 1 + 2 * 3
*/
int pow = 1;
for(int i = toThird.length()-1; i >= 0; i--) {
answer += pow * (toThird.charAt(i) - '0');
pow *= 3;
}
return answer;
}
}
2. 다른 분 풀이
3진법 -> 10진법은 Integer.parseInt를 통해 간단하게 구현한 모습이다.
StringBuilder의 reverse() 함수를 이용해 간단히 뒤집어버린 모습이다.
이하 동일하다.
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);
}
}
'코딩테스트 > Programmers' 카테고리의 다른 글
[프로그래머스] 시저 암호 (0) | 2025.02.26 |
---|---|
[프로그래머스] 이상한 문자 만들기 (0) | 2025.02.26 |
[프로그래머스] 같은 숫자는 싫어 (0) | 2025.02.25 |
[프로그래머스] 문자열 다루기 (0) | 2025.02.25 |
[프로그래머스] 나누어 떨어지는 숫자 배열 (0) | 2025.02.20 |