알고리즘 : C++/SWEA Expert Academy

1288. 새로운 불면증 치료법

동 노이만 2023. 5. 15. 22:12

https://swexpertacademy.com/main/code/problem/problemDetail.do?problemLevel=2&contestProbId=AV18_yw6I9MCFAZN&categoryId=AV18_yw6I9MCFAZN&categoryType=CODE&problemTitle=&orderBy=FIRST_REG_DATETIME&selectCodeLang=ALL&select-1=2&pageSize=10&pageIndex=3

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com

 

풀이 과정

 N을 입력받고 N * i 에 숫자가 들어오면 해당 숫자를 문자열로 변환했다. 이후 문자열 각 자리를 substr()로 추출하고 해당 인덱스 flag를 true로 갱신한다. flag[0] ~ flag[9]를 감시하며 모든 숫자가 들어왔는지 확인하고, 모든 숫자가 들어왔다면 break를 통해 for문을 나가 몇번째 양인지 출력하게 된다.

 

느낀 점

 우선 문제 구상은 바로 떠올랐지만 문자열에서 한 글자씩 추출하는 부분에서 애를 먹었다. substr() 사용법을 따로 찾아봤다. 문자열 함수들에 대한 활용법을 숙지해야할 것 같다. find(), substr() 의 프로토타입을 다시 한번 정리하고 C++ STL에서 제공하지 않는 splite() 구현을 숙지할 필요가 있다. 

 

#include<bits/stdc++.h>
using namespace std;

int cnt, num;
bool flag[10], pass;
string s;

int main() {
	int T;
	cin >> T;
	for (int t = 0; t < T; t++) {
		fill(&flag[0], &flag[0] + 10, false);
		cnt = 0;

		cin >> num;

		for (int i = 1; ; i++) {
			s = to_string(num * i);
			
			for (int j = 0; j < s.size(); j++) {
				int token = stoi(s.substr(j, 1));
				flag[token] = true;
			}

			pass = true;

			for (int j = 0; j < 10; j++) {
				if (flag[j] == false) pass = false;
			}

			if (pass == true) {
				cnt = stoi(s);
				break;
			}
		}
		cout << "#" << t + 1 << " " <<  cnt << "\n";
	}
	return 0;
}