40 lines
741 B
C
40 lines
741 B
C
|
|
#include "libft.h"
|
|
|
|
long long ft_atoll(const char *str)
|
|
{
|
|
long long nbr;
|
|
int i;
|
|
int sign;
|
|
|
|
i = 0;
|
|
sign = 1;
|
|
nbr = 0;
|
|
|
|
// skip leading whitespace
|
|
while (ft_isspace(str[i]))
|
|
i++;
|
|
|
|
// handle optional sign
|
|
if (str[i] == '-')
|
|
sign = -1;
|
|
if (str[i] == '+' || str[i] == '-')
|
|
i++;
|
|
|
|
// parse digits with overflow check for `long long`
|
|
while (str[i] >= '0' && str[i] <= '9')
|
|
{
|
|
// check if multiplying by 10 would overflow
|
|
if (nbr > LLONG_MAX / 10)
|
|
return (sign > 0) ? LLONG_MAX : LLONG_MIN;
|
|
// check if adding the next digit would overflow
|
|
if (nbr == LLONG_MAX / 10 && (str[i] - '0') > LLONG_MAX % 10)
|
|
return (sign > 0) ? LLONG_MAX : LLONG_MIN;
|
|
|
|
nbr = nbr * 10 + (str[i] - '0');
|
|
i++;
|
|
}
|
|
|
|
return (nbr * sign);
|
|
}
|