본문 바로가기

Programming/Programmers

[프로그래머스/C++] 124 나라의 숫자(진법 변환)

3진법인데 사용하는 숫자가 1,2,4

 

#include <iostream>
#include <string>
#include <vector>

using namespace std;

string solution(int n) {
    char nums[3] = {'4','1','2'};
    string answer = "";
    
    while(n){
        answer = nums[n%3] + answer;
        n = n/3 - (n%3==0); 
    }
    
    return answer;
}

 

DFS로 풀었는데 지저분

 

#include <string>
#include <vector>
#include <iostream>

using namespace std;

vector<int> v;
void dfs(int n){
    
    if(n==1){
        v.push_back(1);
        return;
    } 
    else if(n==2){
        v.push_back(2);
        return;
    }
    else if(n==3){
      v.push_back(4);
        return;
    } 
    else{
        
        if(n%3==0){
            int mok = n/3-1;
            int namo = 4;
            v.push_back(namo);
            dfs(mok);
        }
        else{
            int mok= n/3;
            int namo=n%3;
            v.push_back(namo);
            dfs(mok);
        } 
    }
}

string solution(int n) {
    string answer = "";
    dfs(n);
    
    for(int i=v.size()-1;i>=0;i--){
        answer.append(to_string(v[i]));
    }
    return answer;
}