[프로그래머스/Lv2] N진수 게임_C++

1 분 소요

[프로그래머스/Lv2] N진수 게임_C++


문제 내용

  • N진법의 수를 서로 번갈아 가면서 호출한다.
  • m은 명수, p 순번이 되었을 때만 호출을 한다.
  • 호출해야 하는 t개를 말하면 종료한다.



입출력 예

|N|t|m|p|출력| |—|—|—|—|—| |2|4|2|1|”0111”| |16|16|2|1|”02468ACE11111111”| |16|16|2|2|”13579BDF01234567”|



문제 풀이

  • 가독성을 위해 주석으로도 설명하겠다.
  • 각 숫자를 변수로 진법수로 나타내면서 string으로 바꾸어준다.
    • 10진법 이상은 영어대문자가 들어가므로 ascii code로 예외처리해주었다.
    • 나머지를 이어붙이는 방식으로 진행했으므로 reverse를 진행해준다.
  • 숫자를 1씩 증가시키면서 n진법수로 바꾸고 n진법 바꾼수를 차례대로 호출하면서 t개를 다 말했는지 검사한다.



풀이 CODE

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

using namespace std;

string form_change(int num,int n);


string solution(int n, int t, int m, int p) {
    string answer= "";
    int start = 0;
    int count =1;
    
    while(true){
        
        string str = form_change(start,n);
        int size = str.size();
        
        for(int i=0 ; i<size;i++){ // (string)N진법수 t개가 호출 될 때 까지만
            if(count == p)
                answer += str[i];
            count++;
            if(count>m)
                count -= m;
            
            if(answer.size() == t)
                return answer;
        }
        start++;
    }
    
}


string form_change(int num,int n){
    
    string str = "";
    
    while(num/n != 0){
        int res = num%n;
        if(res>=10){
            char c = res + 55;
            str += c; // ascii 숫자->영어대문자            
        }
        else
            str+= to_string(res);
        num /= n;
    }
    
    int res = num%n;
    if(res>=10){
        char c = res + 55;
           str += c; // ascii 숫자->영어대문자            
    } 
    else
        str+= to_string(res);
    
    
    reverse(str.begin(), str.end());
    
    return str;   
        
}

댓글남기기