반응형
문제 링크
https://school.programmers.co.kr/learn/courses/30/lessons/12939
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
풀이 및 코드
전에 풀었지만 1달만에 돌아와 알고리즘을 오랜만에 시작해서 푼 저의 모습(더러운코드 1)을 봤는데 정말 더럽네요..
함수 다 기억못해서 다 일일히 구현을 하고 난리도 아니었네요..
더러운 코드를 보고싶지 않으신분은 아래를 보시길 바랍니다 :)
더러운 코드 1
#include <string>
#include <vector>
using namespace std;
int ft_atoi(char c);
string solution(string s) {
string answer = "";
string str ="";
int min,max;
int num = 0;
if(s[0] == '-'){
int tmp = 0;
while(s[++tmp] != ' '&&s[tmp]){
num *= 10;
num += ft_atoi(s[tmp]);
}
num *= -1;
}else{
int tmp = 0;
while(s[tmp] != ' '&&s[tmp]){
num *= 10;
num += ft_atoi(s[tmp]);
tmp++;
}
}
min = num;
max = num;
for(int i = 0; i < s.length();i++){
num = 0;
if(s[i] == '-'){
while(s[++i] != ' '&&s[i]){
num *= 10;
num += ft_atoi(s[i]);
}
num *= -1;
}else if('0' <= s[i] && s[i] <= '9'){
while(s[i] != ' ' && s[i]){
num *= 10;
num += ft_atoi(s[i]);
i++;
}
}
if(max < num)
max = num;
if(min > num)
min = num;
}
answer += to_string(min);
answer +=" ";
answer += to_string(max);
return answer;
}
int ft_atoi(char c){
return (c - '0');
}
고친 코드
getlin을 하여 공백에 대한 처리를 하여 토큰을 받아옵니다.
받아온 토큰에 대해 stoi를 하여 최댓값과 최솟값을 판별하여 갱신을 하고 마지막에 answer에 push_back을 해줍니다.
위의 코드 정말 대단한 느낌이 드네요..ㅋㅋㅋ
#include <string>
#include <vector>
#include <sstream>
#include <algorithm>
using namespace std;
int ft_atoi(char c);
string solution(string s) {
string answer = "";
int ft_max = -2147483647;
int ft_min = 2147483647;
istringstream iss(s);
string token;
while(getline(iss,token, ' ')){
int num = stoi(token);
if(ft_max < num)
ft_max = num;
if(ft_min > num)
ft_min = num;
}
answer += to_string(ft_min);
answer +=" ";
answer += to_string(ft_max);
return answer;
}
반응형
'알고리즘 > c++ 프로그래머스' 카테고리의 다른 글
[프로그래머스] 올바른괄호 c++ (0) | 2023.05.02 |
---|---|
[프로그래머스] 광물캐기 c++ (0) | 2023.05.02 |
[프로그래머스] 최솟값 만들기 c++ (0) | 2023.05.02 |
[프로그래머스] JadenCase 문자열 만들기 c++ (0) | 2023.05.02 |
[프로그래머스] 연속된 부분 수열의 합 c++ (0) | 2023.05.02 |
댓글