프로그래머스(Level1) - 정수 내림차순으로 배치하기
함수 solution은 정수 n을 매개변수로 입력받습니다. n의 각 자릿수를 큰것부터 작은 순으로 정렬한 새로운 정수를 리턴해주세요. 예를들어 n이 118372면 873211을 리턴하면 됩니다.
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
long long solution(long long n) {
long long answer = 0;
vector<int> num;
string s = to_string(n);
int idx =0;
int digit = 1;
for(int i=0; i<s.length(); i++)
num.push_back(s[i] - '0');
sort(num.begin(), num.end());
while(idx < s.length()){
answer += digit * num[idx];
idx++;
digit *= 10;
}
return answer;
}
string도 sort로 내림차순이 가능하다!! 원래 알고 있던 사실인데 왜 써먹지를 못했지.. 나중에는 꼭 적용해서 풀기를!!
- sort(arr, arr+n);
- sort(arr.begin(), arr.end());
- sort(arr.begin(), arr.end(), compare); //사용자 정의 함수
- sort(arr.begin(), arr.end(), greater<자료형>()); //내림차순
- sort(arr.begin(), arr.end(), less<자료형>()); //오름차순(default)
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
long long solution(long long n) {
long long answer = 0;
string str = to_string(n);
sort(str.begin(), str.end(), greater<char>());
answer = stoll(str);
return answer;
}