GitHubSeob
C++ / 프로그래머스 / [3차] n진수 게임 본문
문제 |
https://school.programmers.co.kr/learn/courses/30/lessons/17687
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
문제풀이 |
16진수까지 숫자를 표현할 수 있으므로 char형 벡터를 만들어 '0'부터 'F'까지 미리 저장한다.
int number(1);
string notation("0");
for (int idx = 0; idx < m * t; ++idx) {
if (notation.empty()) {
notation = itos(number++, n);
}
if (idx % m + 1 == p) answer += notation[0];
notation.erase(0, 1);
}
number는 바꾸기 전 숫자를 저장하는 변수이다.
notation은 number을 해당 진수로 바꾼 string형 변수이다.
notation이 비었으면 다음 번호를 진수로 바꿔야 하므로 따로 만든 itos 함수를 이용해 바꾼 번호를 notation에 저장한다.
p는 1 이상이므로 나머지가 0이 아닌 1 이상으로 나오도록 idx % m에 1을 더한다.
현재 차례가 p의 차례라면 notataion의 맨 앞자리 숫자를 answer에 더한다.
그리고 매 번 erase를 통해 맨 앞자리를 지운다.
코드 |
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
vector<char>v_num = { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' };
string itos(int num, int n) {
string ret("");
while (num > 0) {
ret += v_num[num % n];
num /= n;
}
reverse(ret.begin(), ret.end());
return ret;
}
string solution(int n, int t, int m, int p) {
string answer("");
int number(1);
string notation("0");
for (int idx = 0; idx < m * t; ++idx) {
if (notation.empty()) {
notation = itos(number++, n);
}
if (idx % m + 1 == p) answer += notation[0];
notation.erase(0, 1);
}
return answer;
}
'Programmers > Level 2' 카테고리의 다른 글
C++ / 프로그래머스 / 땅따먹기 (0) | 2023.08.16 |
---|---|
C++ / 프로그래머스 / 주차 요금 계산 (0) | 2023.08.16 |
C++ / 프로그래머스 / [3차] 압축 (0) | 2023.08.10 |
C++ / 프로그래머스 / k진수에서 소수 개수 구하기 (0) | 2023.08.10 |
C++ / 프로그래머스 / 프로세스 (0) | 2023.07.26 |