-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring-to-integer.cs
More file actions
68 lines (63 loc) · 2.12 KB
/
Copy pathstring-to-integer.cs
File metadata and controls
68 lines (63 loc) · 2.12 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
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
public class Solution {
public int MyAtoi(string str) {
int counter = 0;
var ca = str.ToCharArray();
for (int i = 0; i < ca.Length; i++) {
if (ca[i] == ' ')
counter++;
else
break;
}
str = str.Substring(counter, str.Length - counter);
if (str == "")
return 0;
ca = str.ToCharArray();
int firstDigitIndex = -1, endDigitIndex = -1;
for (int i = 0; i < ca.Length; i++) {
if (!isDigit(ca[i]) && ca[i] != '+' && ca[i] != '-')
break;
if (isDigit(ca[i]) && firstDigitIndex < 0) {
firstDigitIndex = i;
endDigitIndex = i;
}
else if (isDigit(ca[i]) && firstDigitIndex >= 0) {
endDigitIndex = i;
}
}
if (firstDigitIndex == -1 || endDigitIndex == -1)
return 0;
bool isSigned = false, isNegative = false;
for (int i = 0; i < firstDigitIndex; i++) {
if (!isDigit(ca[i]) && ca[i] != '+' && ca[i] != '-')
return 0;
if ((ca[i] == '+' && isSigned) || (ca[i] == '-' && isSigned))
return 0;
else if (ca[i] == '-' || ca[i] == '+') {
isSigned = true;
if (ca[i] == '-')
isNegative = true;
}
}
if (firstDigitIndex == 0)
str = str.Substring(firstDigitIndex, endDigitIndex - firstDigitIndex + 1);
else
str = str.Substring(firstDigitIndex - 1, endDigitIndex - firstDigitIndex + 2);
int result;
try {
result = int.Parse(str);
}
catch {
if (!isNegative)
return int.MaxValue;
else
return int.MinValue;
}
return result;
}
private bool isDigit(char c) {
if (c == '0' || c == '1' || c == '2' || c == '3' || c == '4' ||
c == '5' || c == '6' || c == '7' || c == '8' || c == '9')
return true;
return false;
}
}