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

well-life-gm·2021년 12월 21일
0

프로그래머스

목록 보기
101/125

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

10진수 숫자를 n진수로 변환하는 것인 첫 번째 부분.
그 다음 for-loop을 돌면서 t개를 다 채우면 빠르게 break를 걸어주는 것이 두 번째 부분이다.
break를 안걸고 t*m개를 다 구해도 되긴하는데, 그러면 몇몇 TC에서 매우 느리다.(통과는 된다)

코드는 다음과 같다.

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

using namespace std;

void trans(int from, int base, string &to)
{
    while(from) {
        if(from % base >= 10)
            to.push_back(from % base - 10 + 'A');
        else
            to.push_back(from % base + '0');
        from = from / base;
    }
    reverse(to.begin(), to.end());
}
string solution(int n, int t, int m, int p) {
    string answer = "";
    string full = "0";
    for(int i=1,idx=0;i<t*m;i++) {
        string trans_result; trans(i, n, trans_result);
        full += trans_result;
        while((full.size() > idx * m + p - 1) && (idx != t)) {
            answer.push_back(full[idx * m + p - 1]);
            idx++;
        }
        if(idx == t)
            break;
    }
    
    return answer;
}

결과

profile
내가 보려고 만든 블로그

0개의 댓글