알고리즘 & 자료구조/코딩테스트
[프로그래머스] 정수 내림차순으로 배치하기 (C++)
인디아나쥰이
2021. 2. 13. 18:50
문제 설명
함수 solution은 정수 n을 매개변수로 입력받습니다. n의 각 자릿수를 큰것부터 작은 순으로 정렬한 새로운 정수를 리턴해주세요. 예를들어 n이 118372면 873211을 리턴하면 됩니다.
제한 조건
- n은 1이상 8000000000 이하인 자연수입니다.
입출력 예
n return
| 118372 | 873211 |
to_string 과 stoll을 사용하면 간단하게 해결할 수 있다.
그 외 sort에 comp 내용은 이 블로그의 다른글에 정리해두었다.
[C++] sort 함수 compare
sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp); 정렬해주는 함수로 굉장히 사용하기 편하다. 뒤에 compare는 사용하지 않아도 되고, sort (RandomAccessIterator first, RandomAcc..
junecode.tistory.com
stoll 내용 ==>>
[C++]std::stoll
std::stoll string의 내용을 integer타입으로써 분석하고 , long long 타입의 value를 리턴해주는 특정한 규정하에 값을 돌려준다. 헤더 : #include syntax: long long stoll (const string & str, size_t * idx =..
junecode.tistory.com
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
bool comp(int a, int b)
{
return a > b;
}
long long solution(long long n) {
string s;
s = to_string(n);
sort(s.begin(), s.end(), comp);
return stoll(s);
}
//테스트 실행용
int main(void)
{
long long n;
cin >> n;
cout << solution(n);
}728x90
반응형