Skip to content

Commit eb13738

Browse files
authored
[Math] Refactor solution to Atoi
1 parent f5a04ca commit eb13738

File tree

1 file changed

+25
-25
lines changed

1 file changed

+25
-25
lines changed

Math/Atoi.swift

Lines changed: 25 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -6,55 +6,55 @@
66
*/
77

88
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)
1512

1613
// 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 {
2019
break
2120
}
21+
2222
index += 1
2323
}
24-
guard index < content.count else {
24+
25+
guard index < strChars.count else {
2526
return res
2627
}
2728

2829
// handle flag
29-
if content[index] == "-" {
30+
if strChars[index] == "-" {
3031
flag = -1
3132
index += 1
32-
} else if content[index] == "+" {
33+
} else if strChars[index] == "+" {
3334
index += 1
3435
}
3536

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 {
3842
break
3943
}
4044

41-
res = res * 10 + Int(String(content[index]))!
45+
res = res * 10 + currentChar.wholeNumberValue!
4246

43-
if res >= int_max {
47+
if res >= intMax {
4448
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
4852
}
4953
}
50-
54+
5155
index += 1
5256
}
5357

5458
return flag * res
5559
}
56-
57-
private func _isDigit(char: Character) -> Bool {
58-
return char >= "0" && char <= "9"
59-
}
60-
}
60+
}

0 commit comments

Comments
 (0)