atoi 구현

임정우·2023년 8월 3일

Allowed functions : None
Write a function that converts the initial portion of the string pointed by str to its int
representation
• The string can start with an arbitray amount of white space (as determined by isspace(3))
• The string can be followed by an arbitrary amount of + and - signs, - sign will change
the sign of the int returned based on the number of - is odd or even.
• Finally the string can be followed by any numbers of the base 10.
• Your function should read the string until the string stop following the rules and return
the number found until now.
• You should not take care of overflow or underflow. result can be undefined in that case.
• Here’s an example of a program that prints the atoi return value:
$>./a.out " ---+--+1234ab567"
-1234
• Here’s how it should be prototyped : int ft_atoi(char *str);

문제를 요약하면 atoi를 구현하되 앞에 white space (공백문자)를 제거해야하고 +와 -가 몇개 들어올지 모르며, "+-+-1235abc"처럼 뒤에 숫자가 아닌 문자가 온다면 문자 앞의 1235만 반환해야한다.

크게 어려운 것은 없으며 조건대로 하면 된다.

마이너스처리가 조금 헷갈릴 수 있는데, minus 변수를 1로 초기화한 뒤 -를 만날 때마다 -1을 곱해주고 마지막에 최종답에 곱해주어 반환하면 된다.

마지막으로 오버플로우에 관하여 처리하여야한다
정수의 최대값은 21474836487이고 최소값은 -2147483648이다.
방법은
1. str[i] - '0'을 ans에 더해줄 때 minus를 미리 곱해준다.
양수일 때 2147483648를 저장하고 마이너스를 곱해주면 오버플로우가 발생할 것이다.

  1. 그냥 내비둔다. 2147483647에서 1더해서 오버플로우가 나면 어차피 -2147483648이다.

난 2번을 택했다. 좋은 방법인지는 모르겠다 ㅎㅎ;

전체코드:

int	ft_atoi(char *str)
{
	int		minus;
	int		ans;
	int		i;

	minus = 1;
	i = 0;
	while (str[i] == ' ' || (str[i] >= 9 && str[i] <= 13))
		i++;
	while (str[i] == '-' || str[i] == '+')
	{
		if (str[i] == '-')
			minus *= -1;
		i++;
	}
	ans = 0;
	while (str[i] >= '0' && str[i] <= '9')
	{
		ans *= 10;
		ans += (str[i] - '0');
		i++;
	}
	return (minus * ans);
}
profile
경희대학교 소프트웨어융합학과

1개의 댓글

comment-user-thumbnail
2023년 8월 3일

잘 봤습니다. 좋은 글 감사합니다.

답글 달기