題目:實(shí)現(xiàn)一個(gè)函數(shù) stringToInt,實(shí)現(xiàn)把字符串轉(zhuǎn)換成整數(shù)這個(gè)功能曹仗,不能使用系統(tǒng)提供的庫(kù)函數(shù).
題目很簡(jiǎn)單赦肃,不過(guò)需要考慮多種異常輸入的情況,核心代碼如下:
<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>
測(cè)試代碼:
<pre><code>var convert:Convert = Convert() var convertResult:Int? = convert.stringToInt(str: "-9987334") if convertResult != nil { print("FlyElephant--轉(zhuǎn)換結(jié)果---||\(convertResult!)") } else { print("參數(shù)非法") }
</code></pre>