-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.cs
46 lines (45 loc) · 1 KB
/
Solution.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
// https://leetcode.com/problems/string-to-integer-atoi/
public partial class Solution
{
public int MyAtoi(string str)
{
int i = 0;
long result = 0;
bool minus = false;
while (i < str.Length && char.IsWhiteSpace(str[i]))
{
++i;
}
if (i < str.Length)
{
if (str[i] == '+')
{
++i;
}
else if (str[i] == '-')
{
minus = true;
++i;
}
}
while (i < str.Length && char.IsDigit(str[i]))
{
result = result * 10 + str[i] - '0';
if (result > int.MaxValue)
{
break;
}
++i;
}
if (minus) result = -result;
if (result > int.MaxValue)
{
result = int.MaxValue;
}
if (result < int.MinValue)
{
result = int.MinValue;
}
return (int)result;
}
}