[프로그래머스 Level2] 124 나라의 숫자

Wonjun·2022년 7월 25일
0

알고리즘 & 문제풀이

목록 보기
30/50
post-thumbnail

📝 124 나라의 숫자

문제 설명

124 나라의 숫자

해결 방법

3진법으로 문제를 풀면 되는데 0, 1, 2가 아닌 1, 2, 4로 하면 된다. 다만, 0이 없으므로 3으로 나눴을 때 나누어 떨어지는 수만 1씩 빼주면 된다. 뒤에서부터 문자를 이었기 때문에 마지막에 reverse하고 반환한다.

💻소스코드

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

string solution(int n) {
    string answer = "";
    string country = "124";
    while (n > 0) {
        if (n % 3 == 0) {
            answer += country[2];
            n--;
        }
        else if (n % 3 == 1)
            answer += country[0];
        else if (n % 3 == 2) 
            answer += country[1];
        
        n /= 3;
    }
    reverse(answer.begin(), answer.end());
    return answer;
}
profile
알고리즘

0개의 댓글