-
Notifications
You must be signed in to change notification settings - Fork 0
/
0008_String_to_Integer_atoi.cs
46 lines (42 loc) · 1.09 KB
/
0008_String_to_Integer_atoi.cs
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
public class Solution {
public int MyAtoi(string str) {
int n = str.Length;
int p = 0;
while (p < n && str[p] == ' ')
p++;
if (p == n)
return 0;
bool neg = false;
if (str[p] == '-') {
neg = true;
p++;
}
else if (str[p] == '+') {
p++;
}
int lim10;
int limLast;
if (neg) {
lim10 = Math.Abs(int.MinValue / 10);
limLast = 8;
} else {
lim10 = int.MaxValue / 10;
limLast = 7;
}
int ret = 0;
while (p < n && char.IsDigit(str[p])) {
int dig = str[p] - '0';
if (ret > lim10 || ret == lim10 && dig > limLast)
{
if (neg)
return int.MinValue;
else
return int.MaxValue;
}
ret = ret * 10 + dig;
p++;
}
if (neg) ret = -ret;
return ret;
}
}