題目連結: https://leetcode.com/problems/string-to-integer-atoi/
func myAtoi(_ s: String) -> Int {
var negative = false
var result = 0
var start = false
for c in s {
if c == " " {
if start {
break
}
} else if c == "-" || c == "+" {
if start {
break
}
start = true
negative = (c == "-") ? true : false
} else if let val = Int(String(c)) {
start = true
if result > (Int32.max / 10) || (result == (Int32.max / 10) && val > 7) {
return negative ? Int(Int32.min) : Int(Int32.max)
}
result = result * 10 + val
} else {
break
}
}
return negative ? -result : result
}