-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path008-StringToInteger(atoi).cs
51 lines (42 loc) · 1.38 KB
/
008-StringToInteger(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
47
48
49
50
51
//-----------------------------------------------------------------------------
// Runtime: 144ms
// Memory Usage:
// Link:
//-----------------------------------------------------------------------------
namespace LeetCode
{
public class _008_StringToInteger
{
public int MyAtoi(string str)
{
if (string.IsNullOrWhiteSpace(str)) { return 0; }
var navigate = false;
var index = 0;
while (index < str.Length && str[index] == ' ') { index++; }
if (str[index] == '-')
{
navigate = true;
index++;
}
else if (str[index] == '+')
{
index++;
}
var positiveOverflowHead = int.MaxValue / 10;
var positiveOverflowTail = int.MaxValue % 10;
var result = 0;
for (; index < str.Length; index++)
{
var digit = str[index] - '0';
if (digit < 0 || digit > 9) { break; }
if (result > positiveOverflowHead ||
(result == positiveOverflowHead && digit > positiveOverflowTail))
{
return navigate ? int.MinValue : int.MaxValue;
}
result = result * 10 + digit;
}
return navigate ? -result : result;
}
}
}