본문 바로가기
프로그래머스코딩테스트연습풀이/C언어

[프로그래머스/C언어] 문자열로 변환

by 코코쵸마 2023. 8. 2.

문제

정수 n이 주어질 때, n을 문자열로 변환하여 return하도록 solution 함수를 완성해주세요.

 

솔루션

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

char* solution(int n) {
    // return 값은 malloc 등 동적 할당을 사용해주세요. 할당 길이는 상황에 맞게 변경해주세요.
    char* answer = (char*)malloc(1);
    char* sol = (char*)malloc(1);
    int i = 10;
    int j = 0;
    int k;
    while(1){
        sol[j++] = n%10;
        //printf("%d ", n%10);
        n = n / 10;
        if(n/10==0 && n%10==0)
            break;
    }
    for(k = 0; k < j; k++){
        printf("%d: %c\n",j-k-1,sol[j-k-1]+'0');
        answer[k] = sol[j-k-1]+'0';
    }
    answer[k++] = '\0';
    return answer;
}

https://school.programmers.co.kr/learn/courses/30/lessons/181845