본문 바로가기
프로그래머스/Lv.2

[C++] 프로그래머스 [3차] n진수 게임

by MINU.SHINNNN 2023. 10. 9.

https://school.programmers.co.kr/learn/courses/30/lessons/17687

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

풀이

10진수를 n진수로 표현하여 이어붙인 후, 총 참여인원 m과 튜브의 차례 p가 주어졌을 때, 튜브가 말해야하는 t개의 문자를 공백없이 이어붙여 출력해야 하는 문제입니다.

 

n의 범위는 2~16 이기 때문에 16진수까지 표현하기 위한 string 자료형 변수 str을 선언해 둡니다.

총 참여 인원 m과 튜브가 말해야하는 갯수 t가 주어졌을 때 필요한 n진수 최소 문자열 길이는 m*t (min_cnt 변수) 입니다. 

따라서, num 변수를 하나씩 늘려가며 n진수로 변환하고 min_cnt 값 이상이면 변환을 종료합니다.

 

이후, 튜브의 차례에 맞게 t개 만큼 문자를 이어붙여 출력해주면 됩니다.

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

using namespace std;

string str[] = {"0", "1", "2", "3", "4", "5", "6",
               "7", "8", "9", "A", "B", "C", "D","E","F"};

string solution(int n, int t, int m, int p) {
    string answer = "";
    
    int min_cnt = m * t; // 최소 n진수 문자열 갯수
    string num_str = "0";
    int num = 1;
    while (true) {
        int num_copy = num;
        string str_tmp;
        while (num_copy > 0) {
            str_tmp += str[num_copy % n];
            num_copy = num_copy / n;
        }
        reverse(str_tmp.begin(), str_tmp.end());
        num_str += str_tmp;
        num++;
        if (num_str.size() >= min_cnt) break; // 최소 길이 만족시 종료
    }
    
    int cnt = 0;
    for (int i = p-1; i < num_str.size(); i+=m) { // 차례 맞게 이어 붙이기
        answer += num_str[i];
        cnt++;
        if (t == cnt) break;
    }
    return answer;
}