-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmaths.c
More file actions
101 lines (96 loc) · 1.98 KB
/
maths.c
File metadata and controls
101 lines (96 loc) · 1.98 KB
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
95
96
97
98
99
100
101
#include "holberton.h"
/**
* _atoi - convert char to integer
* @s: string to convert
* Return: number calculated
*/
int _atoi(char *s)
{
int ispositive;
int result = -1;
int first_pos = 0;
first_pos = find_pos_num(s);
ispositive = _is_positive(s, first_pos);
result = my_atoi(s, first_pos, first_pos, 0, ispositive);
return (result);
}
/**
* _is_positive - calculate how many negatives has an string
* @s: string to calculate
* @pos: last posicion to check sign
* Return: 1 if is positive 0 if is negative
*/
int _is_positive(char *s, int pos)
{
int negatives = 0;
int contador = 0;
while (contador < pos)
{
if (*(s + contador) == '-')
negatives++;
contador++;
}
return (negatives % 2 == 0);
}
/**
* find_pos_num - find position first number
* @s: string
* Return: position of the first number
*/
int find_pos_num(char *s)
{
int pos = 0;
int value = *(s + pos);
while (!is_digit(value) && value >= 0 && value <= 255 && value != '\0')
{
pos++;
value = *(s + pos);
}
return (pos);
}
/**
* my_atoi - return the number
* @s: string
* @start: initial position
* @current: actual position
* @value: current value
* @ispositive: if the number is positive
* Return: position of the last number
*/
int my_atoi(char *s, int start, int current, int value, int ispositive)
{
int current_v;
int result;
current_v = *(s + current);
if (current_v != '\0' && is_digit(current_v))
{
if (current == start)
{
current_v = ispositive ? (current_v - '0') : -(current_v - '0');
result = my_atoi(s, start, current + 1, current_v, ispositive);
return (result);
}
else
{
if (ispositive)
value = (value * 10) + (current_v - '0');
else
value = (value * 10) - (current_v - '0');
result = my_atoi(s, start, current + 1, value, ispositive);
return (result);
}
}
else
{
return (value);
}
}
/**
* is_digit - determinated if is digit
* @c: character
* Return: 1 if is digit
*/
int is_digit(char c)
{
return ((c >= '0' && c <= '9') ? 1 : 0);
}