coding_test/BAEKJOON
백준 1427번 C / C++ 풀이
CodeJin
2021. 11. 29. 16:55
https://www.acmicpc.net/problem/1427
1427번: 소트인사이드
첫째 줄에 정렬하려고 하는 수 N이 주어진다. N은 1,000,000,000보다 작거나 같은 자연수이다.
www.acmicpc.net
이번에는 입력받은 숫자를 정렬하는 문제. 각 자리수로 분해해서 정렬하면 된다.
// C solution
#include <stdio.h>
#include <stdlib.h>
int compare (const void * a, const void * b) {
int x = *(int *)a;
int y = *(int *)b;
return x < y;
}
int main () {
int temp, len = 0;
int number[10];
scanf("%d", &temp);
for (int i = 0; temp != 0; i++) {
number[i] = temp%10;
temp /= 10;
len++;
}
qsort(number, len, sizeof(int), compare);
for (int i = 0; i < len; i++) {
printf("%d", number[i]);
}
}
// C++ solution
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
int main () {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n;
vector<int> v;
vector<int>::iterator iter;
cin >> n;
while (n) {
v.push_back(n % 10);
n /= 10;
}
sort(v.begin(), v.end(), greater<>());
for (iter = v.begin(); iter != v.end(); iter++)
cout << *iter;
}
22.01.09
지금까지 블로그에 올린 문제를 둘러보다가, 이 문제를 다시 보게 되었는데, 생각해보니 굳이 정수로 받아서 10으로 나눠서 할 필요가 없이 그냥 문자열로 처리하면 되는 일이었다.
#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
using namespace std;
int main () {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
string str;
cin >> str;
sort(str.begin(), str.end(), greater<>());
cout << str;
}