-
Notifications
You must be signed in to change notification settings - Fork 0
/
8. String to Integer (atoi)
104 lines (86 loc) · 2.2 KB
/
8. String to Integer (atoi)
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
102
103
104
class Solution {
public:
int myAtoi(string_view s)
{
int index = 0, ans = 0, d = 0;
const int size = int(s.size());
while(index < size && s[index] == ' ')
{
++index;
}
if(index == size)
{
return 0;
}
int sign = 1;
if(s[index] == '-')
{
sign = -1;
++index;
}
else if(s[index] == '+')
{
++index;
}
while(index < size && '0' <= s[index] && s[index] <= '9')
{
d = int(s[index] - '0');
if(ans < INT_MAX / 10 || ans == INT_MAX / 10 && d <= INT_MAX % 10)
{
ans = ans * 10 + d;
}
else
{
return sign >= 0 ? INT_MAX : INT_MIN;
}
++index;
}
return ans * sign;
}
int myAtoi1(string_view s)
{
int index = 0, ans = 0, d = 0;
const int size = int(s.size());
for(; index < size && s[index] == ' '; ++index);
if(index == size)
{
return 0;
}
if(s[index] == '-')
{
while(++index < size && '0' <= s[index] && s[index] <= '9')
{
d = int(s[index] - '0');
if(ans > INT_MIN / 10 || (ans == INT_MIN / 10 && d <= -(INT_MIN % 10)))
{
ans = ans * 10 - d;
}
else
{
return INT_MIN;
}
}
}
else
{
if(s[index] == '+')
{
++index;
}
while(index < size && '0' <= s[index] && s[index] <= '9')
{
d = int(s[index] - '0');
if(ans < INT_MAX / 10 || (ans == INT_MAX / 10 && d <= INT_MAX % 10))
{
ans = ans * 10 + d;
++index;
}
else
{
return INT_MAX;
}
}
}
return ans;
}
};