본문 바로가기
프로그래머스 C++/Level.1

프로그래머스 Level1. 정수 내림차순으로 배치하기

by yeni_0224 2023. 8. 20.
728x90
반응형

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

long long solution(long long n) {
    long long answer = 0;
    string num = to_string(n);
    sort(num.begin(), num.end());
    reverse(num.begin(), num.end());
    for(int i = num.size(); i > 0; i--){
        answer = stoi(num);
    }
    return answer;
}

계속 풀다가 첫번째로 통과되었지만 core dump가 발생해 다시 수정해야했던 답안

sort 사용해서 end() 부터 begin()까지 넣으려 했지만 여기서 core dump가 발생해 저렇게 작업해준 것이다.

 

새로운 함수를 찾아야했다.

그래서 찾은 함수 : stoll()

#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;

long long solution(long long n) {
    long long answer = 0;
    string num = to_string(n);
    sort(num.begin(), num.end());
    reverse(num.begin(), num.end());
    answer = stoll(num);
    return answer;
}

바로 통과되어버린 것.

전에 경력 있는 개발자 분께서 말씀하시길 프로그래머스 문제는 기능 함수만 알아도 다 풀 수 있다고 했다.

 

정수를 문자로 바꿔준 후 >> 숫자의 크기 순으로 정렬하고 >> 순서를 뒤집어준 후 >> 문자를 다시 정수로 바꾸는

방법을 사용했다.

stoll()

std::stoll(): 이 함수는 함수 호출에서 인수로 제공된 문자열을 long long int로 변환합니다. 내용을 지정된 기본의 정수로 해석하는 str을 구문 분석하며, 이는 long long int 유형의 값으로 반환됩니다.

출처 : https://runebook.dev/ko/docs/cpp/string/basic_string/stol

 

C++ - std::stoi, std::stol, std::stoll 부호 있는 정수 값을 문자열로 해석

Documentation Contributors History

runebook.dev

 

다른 사람들의 풀이를 확인했는데 stoll 함수에 다들 이마탁 하는 듯 하다.

사실 레벨1이라고 하길래 정석적으로 문제를 푼다면 설마 어마어마하게 복잡해지겠어? 라고 의심하면서 문제를 풀려고 했다. 역시나 다른 분들의 풀이를 보니 의심은 트루였고, 의심을 걷어내고 문제를 풀었어야한다.

 

<다른 사람의 풀이>

#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;
}

greater<>은 functional 라이브러리를 추가해줘야하고, sort를 내림차순 정렬하기 위해서 넣어줘야한다고 한다.

 

이 방법을 사용하려고도 했었지만 마지막 answer을 출력하는 과정에서 맞지 않아서 포기했던 방법이다.

https://ansohxxn.github.io/programmers/54/

 

[C++로 풀이] 정수 내림차순으로 배치하기⭐

📌 정수 내림차순으로 배치하기

ansohxxn.github.io

그렇다면 stoll을 사용하지 않고 풀게 된다면 어떻게 해야할까? 다른 사람의 풀이를 확인해보자

#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cmath>

using namespace std;

long long solution(long long n) {
    long long answer = 0;
    vector<long long> v,temp;
    /*string s = to_string(n);
    string temp;
    if(s.size()>=2){
        sort(s.begin(),s.end());
    }

    for(int i=0;i<s.size();i++){
        temp[i]=s[s.size()-i-1];
    }

    answer = (long long)stoi(temp);*/
    while(n!=0){
        v.push_back(n%10);
        n/=10;
    }
    sort(v.begin(),v.end());
    for(int i=0;i<v.size();i++){
        temp.push_back(v[v.size()-i-1]); 
    }
    for(int i=0;i<temp.size();i++){
        answer += temp[temp.size()-i-1]*(long long)pow(10,(double)i);
    }

    return answer;
}

pow 함수를 사용하고 있었는데, 이 또한 내가 시도하고자 했던 방법이다. 허허

#include <string>
#include <vector>

using namespace std;

long long solution(long long n) {
    long long answer = 0;
    vector<int> arr;
    while(true){
        arr.push_back(n%10);
        if(n < 10)
            break;
        else
            n /= 10;
    }
    for(int i = 0; i < arr.size(); i++){
        int max_id = i;
        for(int j = i+1; j < arr.size(); j++){
            if(arr[j] > arr[max_id])
                max_id = j;
        }
        if (max_id != i){
            int temp = arr[max_id];
            arr[max_id] = arr[i];
            arr[i] = temp;
        }
    }
    for(int item: arr)
        answer = answer*10 + item;
    return answer;
}

vector<int>를 하나 만들어 풀기도 하고

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

long long solution(long long n) {
   long long answer = 0LL;

    vector<int> _vector;

    while(true) {
        _vector.push_back(n%10);
        if(n/10==0) {
            break;
        } else {
            n = n/10;
        }
    }
    sort(_vector.begin(), _vector.end(), greater<int>());
    int gop=1;
    while(!_vector.empty()) {
        int value = _vector.back();
        _vector.pop_back();
        answer = answer + value*gop;
        gop=gop*10;
    }

    return answer;
}

pop_back 함수를 사용한 방법도 있었다. pop_back에 대한 간단명료한 설명은 여기서 확인했다.

https://godog.tistory.com/entry/C-vector-%EC%83%9D%EC%84%B1-%EB%B0%8F-%EC%82%BD%EC%9E%85-%EC%82%AD%EC%A0%9C

 

C++ vector 생성 및 삽입, 삭제

C++ vector 생성 및 삽입, 삭제 결과1 코드1 #include #include #include using namespace std; int main() { vector v(5, 1);// length = 5 개를 1로 초기화 vector v2; if (v2.empty()) cout

godog.tistory.com

https://twpower.github.io/77-how-to-use-vector-in-cpp

 

[C++] C++ STL vector 기본 사용법과 예제

Practice makes perfect!

twpower.github.io

728x90
반응형