使用場(chǎng)景
假設(shè)我們的環(huán)境只能存儲(chǔ) 32 位有符號(hào)整數(shù),其數(shù)值范圍是?[?231,? 231?? 1]。如果數(shù)值超過(guò)可表示的范圍,則返回 ?INT_MAX (231?? 1) 或?INT_MIN (?231) 。

代碼實(shí)現(xiàn)
funcmyAtoi(_str:String) ->Int{
? ? ? ? var newStr =String() //記錄數(shù)字字符串
? ? ? ? for i in 0..<str.count {
?? ? ? ? ? ?let startIndex = str.index(str.startIndex, offsetBy: i)?
? ? ? ? ? ? let endIndex = str.index(str.startIndex, offsetBy: i+1)
? ? ? ? ? ? let char = str[startIndex..<endIndex] //根據(jù)開(kāi)始位置跟結(jié)束位置取出單個(gè)字符
? ? ? ? ? ?//char.utf8.first! 。。。將字符轉(zhuǎn)成ASCII碼值
? ? ? ? ? ? if(char.utf8.first! ==32){ ? //空格對(duì)應(yīng)的ASCII碼值
? ? ? ? ? ? ? ? if(newStr.count<1){ ?//當(dāng)空格是第一個(gè)字符時(shí),直接進(jìn)行下一次循環(huán)
?? ? ? ? ? ? ? ? ? continue
? ? ? ? ? ? ? ? }else{//當(dāng)空格不是第一個(gè)字符時(shí),結(jié)束for循環(huán)
?? ? ? ? ? ? ? ? ? break
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }else if(char.utf8.first! ?> 47 && char.utf8.first! < 58){ //判斷字符是否為0-9的數(shù)字
?? ? ? ? ? ? ? ?newStr = newStr + char
? ? ? ? ? ? }elseif(char.utf8.first! == 43|| char.utf8.first! ==45) && newStr.count < 1{
? ? ? ? ? ? ? ?//當(dāng)字符是"+"或"-"時(shí),且newStr為空才將"+"或"-"加入newStr中
? ? ? ? ? ? ? ? newStr = newStr + char
? ? ? ? ? ? }else{?
? ? ? ? ? ? ? ? break
? ? ? ? ? ? }
? ? ? ? }
? ? ? //去除頭尾空格
? ? ? ? newStr = newStr.trimmingCharacters(in: .whitespacesAndNewlines)
? ? ? ? ifnewStr.count<1|| newStr =="-"|| newStr =="+"{
? ? ? ? ? ? return 0
? ? ? ? }
? ? ?//處理數(shù)字字符串轉(zhuǎn)Int溢出的情況
? ? ? ? guard Int(newStr) !=nil else{
? ? ? ? ? ? letoneStr =? newStr[str.index(str.startIndex, offsetBy:0)..
? ? ? ? ? ? ifoneStr =="-"{
? ? ? ? ? ? ? ? returnInt(Int32.min)
? ? ? ? ? ? }
? ? ? ? ? ? return Int(INT32_MAX)
? ? ? ? }
? ? ? ? if Int(newStr)! < Int32.min
? ? ? ? ? ? return Int(Int32.min)
? ? ? ? }else if Int(newStr)! ?> Int32.max{
? ? ? ? ? ? return Int(Int32.max)
? ? ? ? }
? ? ? ? return Int(newStr)!
? ? }
注:這是LeetCode的題目,大家有興趣可以去看原題。入口