[C#][LeetCode] 8. String to Integer (atoi)

外部輸入一個字串,若開頭為數字的話或 +- 符號的話則轉換為 int 的型態,且若超過 int 的最大或最小值則取極限值為準。

我的第一版答案如下:

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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
public class Solution {
public int MyAtoi(string str) {
var arrNum = "0123456789".ToList();
var arrSymbol = "-".ToList();

if (string.IsNullOrWhiteSpace(str))
{
return 0;
}
else
{
str = str.Trim();
}

bool isFirstAddSymbol = (str[0] == '+');

if (isFirstAddSymbol)
{
str = str.Substring(1);
}

if (string.IsNullOrWhiteSpace(str))
{
return 0;
}

bool isFirstNum = (arrNum.IndexOf(str[0]) != -1);
bool isFirstSymbol = (arrSymbol.IndexOf(str[0]) != -1);

if ((isFirstAddSymbol && isFirstSymbol) ||
(!isFirstNum && !isFirstSymbol) ||
(isFirstSymbol && str.All(x => arrNum.IndexOf(x) == -1)) ||
(isFirstSymbol && str.Length > 1 && (arrNum.IndexOf(str[1]) == -1)))
{
return 0;
}

string numString = string.Empty;
str = isFirstSymbol ? str.Substring(1) : str;

for (int i = 0; i < str.Length; i++)
{

bool isNum = (arrNum.IndexOf(str[i]) != -1);

if (!isNum)
{
break;
}

if (numString == "0")
{
numString = str[i].ToString();
}
else
{
numString += str[i].ToString();
}

}

int maxValueLength = int.MaxValue.ToString().Length;
long ans = int.MaxValue;

bool isMoreMax = (numString.Length > maxValueLength) || (long.Parse(numString) > int.MaxValue);

if (!isMoreMax)
{
ans = long.Parse(numString);
}

if (isFirstSymbol && isMoreMax)
{
ans += 1;
}

return Convert.ToInt32(isFirstSymbol ? -ans : ans);
}
}

參考最佳解答後的優化版:

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
public class Solution {
public int MyAtoi(string str) {
str = (str ?? string.Empty).Trim();

if (string.IsNullOrWhiteSpace(str))
{
return 0;
}

bool isMinusSign = (str[0] == '-');
if (isMinusSign || (str[0] == '+'))
{

if ((str.Length == 1) ||
((str.Length > 1) && (str[1] < '0' || str[1] > '9')))
{
return 0;
}

str = str.Substring(1);
}

string numString = string.Empty;
foreach (var item in str)
{
bool isNum = (item >= '0' && item <= '9');

if (!isNum) {
break;
}

if (numString == "0")
{
numString = item.ToString();
}
else
{
numString += item.ToString();
}
}

if (numString == string.Empty)
{
return 0;
}

int maxValueLength = int.MaxValue.ToString().Length;
long ans = int.MaxValue;

bool isMoreMax = (numString.Length > maxValueLength) || (long.Parse(numString) > int.MaxValue);

if (!isMoreMax)
{
ans = long.Parse(numString);
}

if (isMinusSign && isMoreMax)
{
ans += 1;
}

return Convert.ToInt32(isMinusSign ? -ans : ans);
}
}