[프로그래머스/C++]Lv.2 - [3차] n진수

YH J·2023년 9월 28일
0

프로그래머스

목록 보기
160/168

문제 링크

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

내 풀이

일단 n진수로 바꾼 뒤 string으로 변환해주는 함수를 만든다.
16진수는 map으로 A,B,D..F를 구현했다.
사람수 m과 반복할 횟수t를 곱한 값만큼 for문으로 n진수로 변환해서 하나의 string변수에 더해나간다.
그후 p번째를 t만큼 반복해서 answer에 더해준다.

내 코드

#include <string>
#include <vector>
#include <map>
#include <iostream>
using namespace std;

string Change(int n, int num, map<int,char>& sixteen)
{
    string s;
    while(num > 0)
    {
        int a = num % n;
        s = a < 10 ? to_string(a) + s : sixteen[a] + s;  
        num /= n;
    }
    return s;
}

string solution(int n, int t, int m, int p) {
    string answer = "";
    
    map<int,char> sixteen;
    
    for(int i = 0; i < 6; i++)
        sixteen[i + 10] = 'A' + i;
    
    string s = "0";
    
    for(int i = 1; i <= m * t; i++)
        s += Change(n, i, sixteen);
    
    for(p; p <= t * m; p += m)
        answer += s[p - 1];
    
    return answer;
}

다른 사람의 풀이

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

using namespace std;

char number[18] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                   'A', 'B', 'C', 'D', 'E', 'F'};

string number_to_n(int num, int n){
    string result;
    if(num == 0){
        return "0";
    }
    while(num > 0){
        result += number[num % n];
        num /= n;
    }
    reverse(result.begin(), result.end());
    return result;
}

string solution(int n, int t, int m, int p) {
    string answer = "";
    string temp;
    int mt = m * t;
    for(int num = 0; temp.size() <= mt; num++){
        string ngame = number_to_n(num, n);
        temp += ngame;
    }

    for(int i = 0; i < t; i++){
        answer += temp.at((m*i)+(p-1));
    }

    return answer;
}

다른 사람의 풀이 해석

16진수를 할 때 char의 배열로 한 사람도 있고
string nums = "0123456789ABCDEF"; 이게 제일 편한 것 같다.

profile
게임 개발자 지망생

0개의 댓글