链接

    1. fun myAtoi(str: String): Int {
    2. val s = str.trim()
    3. if (s.isEmpty()) return 0 // 字符串为空返回0
    4. var charIndex = 0
    5. val positive = when(s[0]) {
    6. in '0' .. '9' -> true
    7. '+' -> {
    8. charIndex++
    9. true
    10. } // 正数
    11. '-' -> {
    12. charIndex++
    13. false
    14. } // 负数
    15. else -> return 0 // 非有效字符串
    16. }
    17. var result = 0
    18. while (charIndex < s.length && s[charIndex] in '0'..'9') {
    19. val temp = result * 10
    20. // 乘法溢出判断
    21. if (temp / 10 == result) result = temp
    22. else return if (positive) Int.MAX_VALUE else Int.MIN_VALUE
    23. // 循环加法
    24. val num = s[charIndex++] - '0'
    25. result += if(positive) num else -num
    26. // 加法溢出判断
    27. if (positive && result < 0) return Int.MAX_VALUE
    28. if (!positive && result > 0) return Int.MIN_VALUE
    29. }
    30. return result
    31. }