3진법 뒤집기

han.user();·2023년 4월 16일
0

프로그래머스

목록 보기
79/87
post-thumbnail

class Solution {
    public int solution(int n) {
        String ternary = ""; // 3진법으로 변환한 문자열을 저장할 변수
        int answer = 0; // 결과값을 저장할 변수

        // n을 3진법으로 변환하여 ternary 변수에 저장
        while (n > 0) {
            ternary += Integer.toString(n % 3);
            n /= 3;
        }

        // 변환된 3진법 문자열을 뒤집어서 다시 10진법으로 변환
        int pow = 0; // 3의 제곱수를 계산하기 위한 변수
        for (int i = ternary.length() - 1; i >= 0; i--) {
            answer += (ternary.charAt(i) - '0') * Math.pow(3, pow);
            pow++;
        }

        return answer;
    }
}
profile
I'm still hungry.

0개의 댓글