6
6
*/
7
7
8
8
class Atoi {
9
- func myAtoi( str: String ) -> Int {
10
- var res = 0
11
- var flag = 1
12
- var index = 0
13
- let int_max = 2147483647
14
- let int_min = - 2147483648
9
+ func myAtoi( _ str: String ) -> Int {
10
+ var res = 0 , flag = 1 , index = 0
11
+ let intMax = 2147483647 , intMin = - 2147483648 , strChars = Array ( str)
15
12
16
13
// trim
17
- let content = [ Character] ( str. characters)
18
- while index < content. count {
19
- guard content [ index] == " " else {
14
+ while index < strChars. count {
15
+ let currentChar = strChars [ index]
16
+
17
+ // trim
18
+ guard currentChar. isWhitespace else {
20
19
break
21
20
}
21
+
22
22
index += 1
23
23
}
24
- guard index < content. count else {
24
+
25
+ guard index < strChars. count else {
25
26
return res
26
27
}
27
28
28
29
// handle flag
29
- if content [ index] == " - " {
30
+ if strChars [ index] == " - " {
30
31
flag = - 1
31
32
index += 1
32
- } else if content [ index] == " + " {
33
+ } else if strChars [ index] == " + " {
33
34
index += 1
34
35
}
35
36
36
- while index < content. count {
37
- guard _isDigit ( content [ index] ) else {
37
+ // cast to number
38
+ while index < strChars. count {
39
+ let currentChar = strChars [ index]
40
+
41
+ guard currentChar. isNumber else {
38
42
break
39
43
}
40
44
41
- res = res * 10 + Int ( String ( content [ index ] ) ) !
45
+ res = res * 10 + currentChar . wholeNumberValue !
42
46
43
- if res >= int_max {
47
+ if res >= intMax {
44
48
if flag == 1 {
45
- return int_max
46
- } else if res > int_max && flag == - 1 {
47
- return int_min
49
+ return intMax
50
+ } else if flag == - 1 && res > intMax {
51
+ return intMin
48
52
}
49
53
}
50
-
54
+
51
55
index += 1
52
56
}
53
57
54
58
return flag * res
55
59
}
56
-
57
- private func _isDigit( char: Character ) -> Bool {
58
- return char >= " 0 " && char <= " 9 "
59
- }
60
- }
60
+ }
0 commit comments