链接
fun myAtoi(str: String): Int { val s = str.trim() if (s.isEmpty()) return 0 // 字符串为空返回0 var charIndex = 0 val positive = when(s[0]) { in '0' .. '9' -> true '+' -> { charIndex++ true } // 正数 '-' -> { charIndex++ false } // 负数 else -> return 0 // 非有效字符串 } var result = 0 while (charIndex < s.length && s[charIndex] in '0'..'9') { val temp = result * 10 // 乘法溢出判断 if (temp / 10 == result) result = temp else return if (positive) Int.MAX_VALUE else Int.MIN_VALUE // 循环加法 val num = s[charIndex++] - '0' result += if(positive) num else -num // 加法溢出判断 if (positive && result < 0) return Int.MAX_VALUE if (!positive && result > 0) return Int.MIN_VALUE } return result}