https://www.acmicpc.net/problem/5648
5648번: 역원소 정렬
모든 원소가 양의 정수인 집합이 있을 때, 원소를 거꾸로 뒤집고 그 원소를 오름차순으로 정렬하는 프로그램을 작성하세요. 단, 원소를 뒤집었을 때 0이 앞에 선행되는 경우는 0을 생략해야합니
www.acmicpc.net
stoi, atoi 함수의 반환형은 Int형이기 때문에 역원소 정렬 문제에서 사용하면, Out of range 런타임 에러가 발생합니다. 따라서 stol을 사용해야합니다. 직접 stol을 구현하는 방법은 아래와 같습니다.
long long stol(string & str){
long long result = str[0] - 48;
for(int i = 1; i < str.size(); i++){
result = (result * 10) + str[i] - 48;
}
return result;
}
아래는 전체 코드입니다.
#include <bits/stdc++.h>
using namespace std;
long long arr[1000001];
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
int n; cin >> n;
for(int i = 0; i < n; i++){
string str; cin >> str;
reverse(str.begin(), str.end()); // 거꾸로 뒤집음
arr[i] = stol(str); // long long형으로 변환
}
sort(arr, arr + n); // 정렬
for(int i = 0 ; i < n; i++) cout << arr[i] << "\n";
}
'Algorithm' 카테고리의 다른 글
[백준 7795번] 먹을 것인가 먹힐 것인가 (C++) (0) | 2022.04.12 |
---|---|
[백준 1431번] 시리얼 번호 (C++) (0) | 2022.04.12 |
[백준 11652번] 카드 (C++) (0) | 2022.04.12 |
[백준 1541번] 잃어버린 괄호 (C++) (0) | 2022.04.07 |
[백준 11660번] 구간 합 구하기 5 (C++) (0) | 2022.04.07 |