Swfit字符串轉(zhuǎn)整數(shù)

使用場(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的題目,大家有興趣可以去看原題。入口

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容