forked from NilaakashSingh/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Atoi.swift
60 lines (48 loc) · 1.51 KB
/
Atoi.swift
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
/**
* Question Link: https://leetcode.com/problems/string-to-integer-atoi/
* Primary idea: Trim, positive and negative, integer overflow, is character digit
*
* Time Complexity: O(n), Space Complexity: O(1)
*/
class Atoi {
func myAtoi(_ str: String) -> Int {
var res = 0, flag = 1, index = 0
let intMax = 2147483647, intMin = -2147483648, strChars = Array(str)
// trim
while index < strChars.count {
let currentChar = strChars[index]
// trim
guard currentChar.isWhitespace else {
break
}
index += 1
}
guard index < strChars.count else {
return res
}
// handle flag
if strChars[index] == "-" {
flag = -1
index += 1
} else if strChars[index] == "+" {
index += 1
}
// cast to number
while index < strChars.count {
let currentChar = strChars[index]
guard currentChar.isNumber else {
break
}
res = res * 10 + currentChar.wholeNumberValue!
if res >= intMax {
if flag == 1 {
return intMax
} else if flag == -1 && res > intMax {
return intMin
}
}
index += 1
}
return flag * res
}
}