generated from eyamenko/dotnet-template-repository
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem57.cs
64 lines (55 loc) · 1.45 KB
/
Problem57.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
52
53
54
55
56
57
58
59
60
61
62
63
64
namespace LeetCode;
/// <summary>
/// <see href="https://leetcode.com/problems/string-to-integer-atoi/">String to Integer (atoi)</see>.
/// </summary>
public static class Problem57
{
/// <summary>
/// Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function).
/// Time complexity: O(n).
/// Space complexity: O(1).
/// </summary>
/// <param name="s">String to traverse.</param>
/// <returns>Converted integer.</returns>
public static int MyAtoi(string s)
{
var (i, converted) = (0, 0);
for (; i < s.Length; i++)
{
if (s[i] != ' ')
{
break;
}
}
if (i >= s.Length)
{
return converted;
}
var isPositive = s[i] != '-';
if (s[i] == '+' || !isPositive)
{
i++;
}
for (; i < s.Length; i++)
{
var digit = s[i] - '0';
if (digit is < 0 or > 9)
{
break;
}
try
{
checked
{
converted *= 10;
converted += digit;
}
}
catch (OverflowException)
{
return isPositive ? int.MaxValue : int.MinValue;
}
}
return isPositive ? converted : -converted;
}
}