-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_atoi.c
83 lines (77 loc) · 1.97 KB
/
ft_atoi.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_atoi.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: arcanava <arcanava@student.42barcel> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/01/12 09:04:02 by arcanava #+# #+# */
/* Updated: 2024/05/01 15:10:38 by arcanava ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int is_allowed_char(char c)
{
return (c == '\t'
|| c == '\n'
|| c == '\v'
|| c == '\f'
|| c == '\r'
|| c == ' '
|| c == '-'
|| c == '+');
}
int ft_atoi(const char *str)
{
long num;
int i;
int is_negative;
int symbols_count;
symbols_count = 0;
num = 0;
i = 0;
is_negative = 0;
while (str[i] != '\0' && is_allowed_char(str[i]) && symbols_count == 0)
{
if (str[i] == '-' || str[i] == '+')
symbols_count++;
if (str[i] == '-')
is_negative = 1;
i++;
}
while (str[i] != '\0' && ft_isdigit(str[i]))
{
num *= 10;
num += str[i++] - '0';
}
if (is_negative)
num *= -1;
return (num);
}
long ft_atol(const char *str)
{
long num;
int i;
int is_negative;
int symbols_count;
symbols_count = 0;
num = 0;
i = 0;
is_negative = 0;
while (str[i] != '\0' && is_allowed_char(str[i]) && symbols_count == 0)
{
if (str[i] == '-' || str[i] == '+')
symbols_count++;
if (str[i] == '-')
is_negative = 1;
i++;
}
while (str[i] != '\0' && ft_isdigit(str[i]))
{
num *= 10;
num += str[i++] - '0';
}
if (is_negative)
num *= -1;
return (num);
}