Muscardinus

[프로그래머스] 최댓값과 최솟값 (Lv2) 본문

알고리즘 문제/[프로그래머스] Lv2

[프로그래머스] 최댓값과 최솟값 (Lv2)

Muscardinus 2020. 7. 15. 13:51
728x90

https://programmers.co.kr/learn/courses/30/lessons/12939

 

문제 설명

문자열 s에는 공백으로 구분된 숫자들이 저장되어 있습니다. str에 나타나는 숫자 중 최소값과 최대값을 찾아 이를 (최소값) (최대값)형태의 문자열을 반환하는 함수, solution을 완성하세요.
예를들어 s가 1 2 3 4라면 1 4를 리턴하고, -1 -2 -3 -4라면 -4 -1을 리턴하면 됩니다.

제한 조건

  • s에는 둘 이상의 정수가 공백으로 구분되어 있습니다.

입출력 예

s return
1 2 3 4 1 4
-1 -2 -3 -4 -4 -1
-1 -1 -1 -1

 

C++

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

using namespace std;

string solution(string s) {
    string answer = "";
    vector<int> v;
    int c=0;
    for(int i=0;i<s.size();i++){
        if(s[i]==' '){
            v.push_back(stoi(s.substr(c,i)));
            c=i+1;
        }
    }
    v.push_back(stoi(s.substr(c,s.size())));
    sort(v.begin(),v.end());
    answer+=to_string(v.front());
    answer+=" ";
    answer+=to_string(v.back());
    return answer;
}

 

JavaScript

function solution(s) {
    var answer = '';
    s=s.split(" ").sort((a,b)=>a-b);
    answer=s[0]+" "+s[s.length-1];
    return answer;
}

 

function solution(s) {
    var answer = '';
    s=s.split(" ");
    return Math.min(...s)+" "+Math.max(...s);
//     string에도 Math함수 적용 가능
}
728x90
Comments