题目:实现一个函数 stringToInt,实现把字符串转换成整数这个功能,不能使用系统提供的库函数.
题目很简单,不过需要考虑多种异常输入的情况,核心代码如下:
<pre><code>`
func stringToInt(str:String?)->Int? {
if str == nil || str?.characters.count == 0 {
return nil
}
var result:Int = 0
var begin:Int = 0
let count:Int = str!.characters.count
var flag:Int = 1
let curStr:String = str![0]
if curStr == "+" {
flag = 1
begin = 1
} else if curStr == "-" {
flag = -1
begin = 1
} else if !isNumberDigit(str: curStr) {
return nil
}
for i in begin..<count {
let curStr:String = str![i]
if !isNumberDigit(str: curStr) {
return nil
}
let temp:Int = Int(curStr)!
if flag == 1 && result > (Int.max - temp * flag) / 10 {
return nil
}
if flag == -1 && result < (Int.min - temp * flag) / 10 {
return nil
}
result = result * 10 + temp * flag
}
return result
}
func isNumberDigit(str:String)->Bool {
return str >= "0" && str <= "9"
}`</code></pre>
测试代码:
<pre><code>var convert:Convert = Convert() var convertResult:Int? = convert.stringToInt(str: "-9987334") if convertResult != nil { print("FlyElephant--转换结果---||\(convertResult!)") } else { print("参数非法") }
</code></pre>