문제

https://www.acmicpc.net/problem/9417
9417번: 최대 GCD
첫째 줄에 테스트 케이스의 개수 N (1 < N < 100)이 주어진다. 각 테스트 케이스는 한 줄로 이루어져 있으며, 양의 정수 M (1 < M < 100)개가 주어진다. 모든 수는 -231보다 크거나 같고, 231 -1보다 작거나
www.acmicpc.net
코드
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int gcd(int a, int b){
while(b!=0){
int c=a%b;
a=b;
b=c;
}
return a;
}
int main(){
int n;
string s;
cin >> n;
cin.ignore();
while(n--){
int result = 0;
vector<int> v;
getline(cin, s);
string a;
int cur_pos=0;
int pos=s.find(' ', cur_pos);
while(pos!=string::npos){
a=s.substr(cur_pos,pos-cur_pos);
v.push_back(stoi(a));
pos=s.find(' ', cur_pos);
cur_pos=pos+1;
}
for(int i=0; i<v.size()-1; i++){
for(int j=i+1; j<v.size(); j++){
if(gcd(v[i],v[j])>result) result=gcd(v[i],v[j]);
}
}
cout << result << '\n';
}
return 0;
}
정리
공백을 기준으로 구분하는 것을 구현하는 것이 까다로웠다. substr()과 find()를 활용해 구현하는 방법을 기억하고 있어야겠다.
int pos=s.find(' ', cur_pos);
while(pos!=string::npos){
a=s.substr(cur_pos,pos-cur_pos);
v.push_back(stoi(a));
pos=s.find(' ', cur_pos);
cur_pos=pos+1;
}
참조
'Beakjoon > string' 카테고리의 다른 글
| [백준] 1551번 수열의 변화 (C++) - stringstream, split (0) | 2022.06.07 |
|---|---|
| [백준] 2998번 8진수 (C++) - str.insert(), str.substr() (0) | 2022.04.27 |
| [백준] 2857번 FBI (C++) - str.find() (0) | 2022.03.05 |
| [백준] 11656번 접미사 배열 (C++) - str.substr() (0) | 2022.03.05 |
| [백준] 10809번 알파벳 찾기 (C++) (0) | 2021.12.29 |