(LeedCode)8. String to Integer (atoi)

    xiaoxiao2026-08-11  12

    public int myAtoi(String str) { if (str.isEmpty()) return 0; str = str.trim(); //去除字符串两端空格 int i = 0, ans = 0, sign = 1, len = str.length(); if (str.charAt(i) == '-' || str.charAt(i) == '+') sign = str.charAt(i++) == '+' ? 1 : -1; for (; i < len; ++i) { int tmp = str.charAt(i) - '0'; if (tmp < 0 || tmp > 9) break; if (ans > Integer.MAX_VALUE / 10 || (ans == Integer.MAX_VALUE / 10 && Integer.MAX_VALUE % 10 < tmp)) //是否会溢出的判断 return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE; else ans = ans * 10 + tmp; } return sign * ans; }
    转载请注明原文地址: https://ju.6miu.com/read-1311083.html
    最新回复(0)