코딩테스트-문자열을 정수로 바꾸기, C언어, itoa()

728x90
반응형

문자열 str을 정수형으로 변환하는 문제,

 

1. str의 맨 앞에는 부호가 올 수 있다.

2. s는 부호와 숫자로만 이루어져 있다.

3. str은 0으로 시작하지 않는다.

 

조건들이 있지만 주의해야할 내용은 없는것 같다. 

 

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

int solution(const char* s) {
    int answer = 0;
    
    answer=atoi(s);
    return answer;
}

atoi 함수를 사용하면 해결된다. Ascii to Integer 함수다.

 

다른 방법으로는

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

int solution(const char* s) {
    int answer = 0;
    sscanf(s, "%d", &answer);
    return answer;
}

 

sscanf는 문자열을 %x, %f, %o 등 다양한 형식의 숫자로 변경할 수 있다. 반면 atoi, ftoi는 데이터 포맷마다 함수를 다르게 사용해줘야한다. 

 

- 끝 -

728x90
반응형