programmers.co.kr/learn/courses/30/lessons/12925
코딩테스트 연습 - 문자열을 정수로 바꾸기
문자열 s를 숫자로 변환한 결과를 반환하는 함수, solution을 완성하세요. 제한 조건 s의 길이는 1 이상 5이하입니다. s의 맨앞에는 부호(+, -)가 올 수 있습니다. s는 부호와 숫자로만 이루어져있습니
programmers.co.kr
- memcpy()만을 이용해 코드를 구현하였고, atoi등을 이용하면 편리할 것이다.
더보기
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
int convert(char ch)
{
switch (ch)
{
case '1':
return 1;
case '2':
return 2;
case '3':
return 3;
case '4':
return 4;
case '5':
return 5;
case '6':
return 6;
case '7':
return 7;
case '8':
return 8;
case '9':
return 9;
case '0':
return 0;
default:
break;
}
}
// 파라미터로 주어지는 문자열은 const로 주어집니다. 변경하려면 문자열을 복사해서 사용하세요.
int solution(const char* s) {
int answer = 0;
int sLen = strlen(s);
char buff[6] = { "\0", };
memcpy(buff, s, sLen);
bool bIsPlus = false;
if ('-' != buff[0])
bIsPlus = true;
int startIndx = 0;
if ('+' == buff[0] || '-' == buff[0])
startIndx++;
int multi = 1;
for (int idx = 0; idx < (sLen - startIndx) - 1; idx++)
{
multi *= 10;
}
for (int idx = startIndx; idx < sLen; idx++)
{
int val = convert(buff[idx]);
val = multi * val;
answer += val;
multi /= 10;
}
if (false == bIsPlus)
answer *= -1;
return answer;
}
int main()
{
int ans = solution("-1234");
printf("%d\n", ans);
return 0;
}
'Coding Problem > 프로그래머스' 카테고리의 다른 글
[프로그래머스/Lv1] - 수박수박수박수박수박수? (0) | 2021.04.29 |
---|---|
[프로그래머스/Lv1] - 예산 (0) | 2021.04.25 |
[프로그래머스/Lv1] - 내적 (0) | 2021.04.25 |
[프로그래머스/Lv1] - 음양 더하기 (0) | 2021.04.25 |
[프로그래머스/Lv1] - 두 개 뽑아서 더하기 (0) | 2021.04.25 |