문자열 my_string이 매개변수로 주어질 때, my_string 안에 있는 숫자만 골라 오름차순 정렬한 리스트를 return 하도록 solution 함수를 작성해보세요.
C언어
주어진 문자열을 받고 하나씩 숫자인지 알파벳인지 구분을 하는 작업이 필요하다.
isdigit() 함수를 통해 문자열의 길이 만큼 구분하는 작업을 반복한다.
문자열에서 숫자는 기본적으로 아스키 코드 값이기 때문에 0의 아스키 코드 값을 빼어 정수로 만들어준다.
숫자라면 answer 배열에 저장하고 다음 for문으로 넘어가서 버블정렬을 해준다.
다음으로 넘어갈 때마다 정렬이 완료된 부분을 제외하고 for문으로 반복하며 또 정렬한다.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
// 파라미터로 주어지는 문자열은 const로 주어집니다. 변경하려면 문자열을 복사해서 사용하세요.
int* solution(const char* my_string) {
// return 값은 malloc 등 동적 할당을 사용해주세요. 할당 길이는 상황에 맞게 변경해주세요.
int len = strlen(my_string);
int* answer = (int*)malloc(len * sizeof(int));
int idx = 0;
for(int i=0; i<len; i++){
if(isdigit(my_string[i])){
answer[idx++] = my_string[i] - '0';
}
}
for(int i = 0; i < idx - 1; i++) {
for(int j = 0; j < idx - i - 1; j++) {
if(answer[j] > answer[j + 1]) {
int tmp = answer[j];
answer[j] = answer[j + 1];
answer[j + 1] = tmp;
}
}
}
return answer;
}
파이썬
주어지는 문자열을 반복하며 isdigit 함수를 통해 숫자를 구분한다.
문자열 형태를 int를 적용하여 정수로 바꿔준 뒤 append로 answer에 리스트 형태로 추가한다.
마지막으로 sort를 사용해 정렬해주면 끝!
def solution(my_string):
answer = []
for char in my_string:
if char.isdigit():
answer.append(int(char))
answer.sort()
return answer