-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringToIntLeetCode.cs
More file actions
43 lines (39 loc) · 1.04 KB
/
Copy pathStringToIntLeetCode.cs
File metadata and controls
43 lines (39 loc) · 1.04 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
namespace algorithms.LeetCode;
public class StringToIntLeetCode
{
public int MyAtoi(string s)
{
var trimmed = s.Trim(' ');
bool isNegative = s.StartsWith('-');
if(string.IsNullOrEmpty(trimmed)) return 0;
string result = string.Empty;
foreach(var c in trimmed)
{
if((c >= '0' && c <= '9'))
{
result += c;
}
else if((c == '+' || c == '-') && trimmed.StartsWith(c))
{
result += c;
}
else break;
}
if(result.IsNullOrEmpty() || !result.Any(c => c >= '0' && c <= '9')) return 0;
if(isNegative)
{
if(Int32.MinValue.ToString().Length <= result.Length)
{
return Int32.MinValue;
}
}
else
{
if(Int32.MaxValue.ToString().Length <= result.Length)
{
return Int32.MaxValue - 1;
}
}
return Convert.ToInt32(result);
}
}