力扣练习之字符串转换整数 (atoi)

我爱海鲸 2022-08-12 16:44:49 暂无标签

简介初级算法、字符串

原题出处:https://leetcode.cn/leetbook/read/top-interview-questions-easy/xnoilh/

解法一:

    public int myAtoi(String s) {
        if (s == null || s.trim().isEmpty()) {
            return 0;
        }
        int length = s.length();
        int index = 0;
        while (index < length && s.charAt(index) == ' ') {
            index ++;
        }
        if (Character.isLetter(s.charAt(index))) {
            return 0;
        }
        char sign = s.charAt(index);
        if (sign == '+' || sign == '-') {
            index ++;
        }
        int result = 0;
        int nextResult;
        while (index < length && s.charAt(index) >= '0' && s.charAt(index) <= '9') {
            nextResult = result;
            result = 10 * result + s.charAt(index) - '0';
            if (sign == '-') {
                if (-result == Integer.MIN_VALUE) {
                    return Integer.MIN_VALUE;
                }
            } else {
                if (result == Integer.MIN_VALUE) {
                    return Integer.MAX_VALUE;
                }
            }
            if ((Math.abs(result)-(s.charAt(index) - '0'))/10 != nextResult) {
                      if (sign == '-') {
                          return Integer.MIN_VALUE;
                      } else {
                          return Integer.MAX_VALUE;
                      }
            }
            index ++;
        }
        if (sign == '-') {
            result = -result;
        }
        return result;
    }

思路:将字符串看作字符数组,判断每一个字符数组,定义一个下标索引,每次校验完当前的字符就将下标标索引加一,最终的结果是返回一个int类型的整型,所以运算的每一个字符都需要在'0'到'9'之间,注意的点,运算后的结果可能会溢出,需要对边界值和溢出后的值进行校验。

你好:我的2025