https://leetcode-cn.com/problems/string-to-integer-atoi/
func myAtoi(_ str: String) -> Int {
if str.count <= 0 {return 0}
var result = 0
var numLength = 0
var minusTimes = 0
var minusFlag = 0
for (_, char) in str.enumerated() {
if (char == "-" || char == "+") && numLength == 0 {
//正负号
minusTimes = minusTimes + 1
minusFlag = char == "-" ? 1 : 0
} else if (isValidNumStr(char) && minusTimes < 2) {
//+ - 只出现一次 其余全数字
result = result * 10 + changeNumValue(char)
numLength = numLength + 1
if result - 1 > Int32.max {break}
} else if (char == " " && numLength == 0 && minusTimes == 0) {
//一直空格
continue
} else {
//其他非数字
break
}
}
if minusFlag == 1 {
return -result < Int32.min ? Int(Int32.min) : -result
}
return result > Int32.max ? Int(Int32.max) : result
}
func isValidNumStr(_ firstStr: Character) -> Bool {
if firstStr == "0" || firstStr == "1" || firstStr == "2" || firstStr == "3" || firstStr == "4" || firstStr == "5" || firstStr == "6" || firstStr == "7" || firstStr == "8" || firstStr == "9" {
return true
} else {
return false
}
}
func changeNumValue(_ str: Character) -> Int {
var result = 0
switch str {
case "0":
result = 0
case "1":
result = 1
case "2":
result = 2
case "3":
result = 3
case "4":
result = 4
case "5":
result = 5
case "6":
result = 6
case "7":
result = 7
case "8":
result = 8
case "9":
result = 9
default:
result = 0
}
return result
}
网友评论