Skip to content

Commit ae32a3d

Browse files
authored
feat: add swift implementation to lcof problem: No.67 (#2962)
1 parent 675b557 commit ae32a3d

File tree

2 files changed

+93
-0
lines changed

2 files changed

+93
-0
lines changed

lcof/面试题67. 把字符串转换成整数/README.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -282,6 +282,55 @@ public class Solution {
282282
}
283283
```
284284

285+
#### Swift
286+
287+
```swift
288+
class Solution {
289+
func strToInt(_ str: String) -> Int {
290+
let n = str.count
291+
if n == 0 {
292+
return 0
293+
}
294+
295+
var index = str.startIndex
296+
while index != str.endIndex && str[index] == " " {
297+
index = str.index(after: index)
298+
}
299+
300+
if index == str.endIndex {
301+
return 0
302+
}
303+
304+
var sign = 1
305+
if str[index] == "-" {
306+
sign = -1
307+
index = str.index(after: index)
308+
} else if str[index] == "+" {
309+
index = str.index(after: index)
310+
}
311+
312+
var result = 0
313+
let flag = Int(Int32.max) / 10
314+
315+
while index != str.endIndex {
316+
let char = str[index]
317+
if char < "0" || char > "9" {
318+
break
319+
}
320+
321+
if result > flag || (result == flag && char > "7") {
322+
return sign == 1 ? Int(Int32.max) : Int(Int32.min)
323+
}
324+
325+
result = result * 10 + Int(char.asciiValue! - Character("0").asciiValue!)
326+
index = str.index(after: index)
327+
}
328+
329+
return sign * result
330+
}
331+
}
332+
```
333+
285334
<!-- tabs:end -->
286335

287336
<!-- solution:end -->
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
class Solution {
2+
func strToInt(_ str: String) -> Int {
3+
let n = str.count
4+
if n == 0 {
5+
return 0
6+
}
7+
8+
var index = str.startIndex
9+
while index != str.endIndex && str[index] == " " {
10+
index = str.index(after: index)
11+
}
12+
13+
if index == str.endIndex {
14+
return 0
15+
}
16+
17+
var sign = 1
18+
if str[index] == "-" {
19+
sign = -1
20+
index = str.index(after: index)
21+
} else if str[index] == "+" {
22+
index = str.index(after: index)
23+
}
24+
25+
var result = 0
26+
let flag = Int(Int32.max) / 10
27+
28+
while index != str.endIndex {
29+
let char = str[index]
30+
if char < "0" || char > "9" {
31+
break
32+
}
33+
34+
if result > flag || (result == flag && char > "7") {
35+
return sign == 1 ? Int(Int32.max) : Int(Int32.min)
36+
}
37+
38+
result = result * 10 + Int(char.asciiValue! - Character("0").asciiValue!)
39+
index = str.index(after: index)
40+
}
41+
42+
return sign * result
43+
}
44+
}

0 commit comments

Comments
 (0)