实现一个 func myAtoi(_ str: String) -> Int 函数,篇学使其能将字符串转换成一个 32 位有符号整数(类似 C/C++ 中的符串 atoi 函数)。 函数 func myAtoi(_ str: String) -> Int 的转换整数算法如下: 注意: 除前导空格或数字后的其余字符串外,请勿忽略 任何其他字符。 示例 1 示例 2 示例 3 示例 4 示例 5 约束条件: 该算法题解的仓库:LeetCode-Swift[2]1. 描述
2. 示例
3. 答案
class Atoi { func myAtoi(_ str: String) -> Int { var res = 0, flag = 1, index = 0 let intMax = 2147483647, intMin = -2147483648, strChars = Array(str) // trim while index < strChars.count { let currentChar = strChars[index] // trim guard currentChar.isWhitespace else { break } index += 1 } guard index < strChars.count else { return res } // handle flag if strChars[index] == "-" { flag = -1 index += 1 } else if strChars[index] == "+" { index += 1 } // cast to number while index < strChars.count { let currentChar = strChars[index] guard currentChar.isNumber else { break } res = res * 10 + currentChar.wholeNumberValue! if res >= intMax { if flag == 1 { return intMax } else if flag == -1 && res > intMax { return intMin } } index += 1 } return flag * res } } 主要思想:修剪,正和负,整数溢出,是字符数字 时间复杂度:O(n) 空间复杂度:O(1)