C# 3진법 뒤집기 - 프로그래머스 [Lv.1]

출처: 프로그래머스 코딩 테스트 연습
https://school.programmers.co.kr/learn/courses/30/lessons/68935

 

 

나의 풀이

using System;
using System.Collections.Generic;

public class Solution {
    public int solution(int n) {
        
        // 10진법 -> 3진법 반전 리스트
        List<int> triList = new List<int>();
        int remain = n;
        while(remain > 0)
        {
            triList.Add(remain % 3);
            remain /= 3;
        }
        
        // 3진법 반전리스트 -> 10진법
        int answer = 0;
        for(int i = 0; i < triList.Count; i++)
            answer += (int)Math.Pow(3, triList.Count - i - 1) * triList[i];
        
        return answer;
    }
}

Convert.ToString(int, int) 는 2의 승수 진법에만 사용가능해서 직접 구했다.

 

 

다른사람 풀이

using System;

public class Solution {
    public int solution(int n) {
        int answer=0;
    while(n>0){
        answer*=3;
        answer+=n%3;
        n/=3;
    }
    return answer;
    }
}

while문 내에서 n의 10진수 -> 3진수, answer의 3진수 -> 10진수가 동시에 이루어진다.

 

 

댓글

Designed by JB FACTORY