-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path100-atoi.c
94 lines (77 loc) · 1.43 KB
/
100-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
84
85
86
87
88
89
90
91
92
93
94
#include "main.h"
/**
* _strlen - get len
* @str: char pointer
* Return: int
*/
int _strlen(char *str)
{
return (strlen(str));
}
/**
* _num_id - find index where a digit is first found in string
* @s: string to search
* Return: integer index where digit is first found
*/
int _num_id(char *s)
{
int i;
for (i = 0; i < _strlen(s); i++)
{
if (s[i] >= '0' && s[i] <= '9')
return (i);
}
return (-1); /* return -1 if no digits found */
}
/**
* find_sign - determine if integer is negative
* @s: integer
* Return: integer 1 or -1
*/
int find_sign(char *s)
{
int negatives = 0, i = 0, sign = 1;
while (i < (_num_id(s)))
{
if (s[i++] == '-')
negatives++;
}
if (negatives % 2 != 0)
sign = -1;
return (sign);
}
/**
* _atoi - convert string to int
* @s: string to convert
* Return: integer
*/
int _atoi(char *s)
{
int _start_id = (_num_id(s));
int sign;
int _digits = 0;
int t = 1, i;
unsigned int num = 0;
int digit = (_num_id(s));
if (_start_id < 0) /* if no digits found, exit program */
return (0);
sign = find_sign(s);
while ((s[_start_id] >= '0' && s[_start_id] <= '9')
&& (_start_id <= _strlen(s))) /* count digits to print */
{
_digits += 1;
_start_id++;
}
i = 1;
while (i < _digits) /* find powers of ten to multiply places */
{
t *= 10;
i++;
}
for (i = digit; i < (digit + _digits); i++) /* calculate num */
{
num += (s[i] - '0') * t;
t /= 10;
}
return (num * sign);
}