File tree Expand file tree Collapse file tree 2 files changed +93
-0
lines changed Expand file tree Collapse file tree 2 files changed +93
-0
lines changed Original file line number Diff line number Diff line change @@ -282,6 +282,55 @@ public class Solution {
282
282
}
283
283
```
284
284
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
+
285
334
<!-- tabs:end -->
286
335
287
336
<!-- solution:end -->
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments