-
Notifications
You must be signed in to change notification settings - Fork 1
/
_atoi.c
46 lines (45 loc) · 783 Bytes
/
_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
#include "shell.h"
/**
* _atoi - Convert a string to an integer
* @s: string to convert
*
* Return: The integer
*/
int _atoi(char *s)
{
int i, start, negative;
unsigned int number;
start = -1;
negative = 0;
number = 0;
for (i = 0; s[i] != '\0'; i++)
{
if (s[i] >= '0' && s[i] <= '9')
start = i;
if (s[i] == '-' && start == -1)
{
if (negative)
negative = 0;
else
negative = 1;
}
}
if (start != -1)
{
for (i = 0; s[i] != '\0'; i++)
{
if (s[i] >= '0' && s[i] <= '9')
number = number * 10 + s[i] - '0';
else if (s[i - 1] >= '0' && s[i - 1] <= '9')
break;
}
}
if ((number >= (unsigned int) INT_MAX && negative == 0))
return (INT_MAX);
else if ((number > (unsigned int) INT_MAX && negative))
return (INT_MIN);
else if (negative)
return ((int) -number);
else
return ((int) number);
}