Under my umbrella.

SKII

Less is more.

力扣题解 8th 字符串转换整数 (atoi)

8th 字符串转换整数 (atoi)

  • 字符串模式匹配

    这种题目极易写出臃肿的代码,我们需要明确具体的条件,并充分考虑细节。(否则会被样例虐爆)

    这里有一个常用的判断溢出条件的方法,在之前的题目中也有出现。

    • 对于正数:

      if(number > Integer.MAX_VALUE / 10 || (number == Integer.MAX_VALUE / 10 && next_index > 7)) return "溢出";

    • 对于负数:

      if(number < Integer.MIN_VALUE / 10 || (number == Integer.MIN_VALUE / 10 && next_index < -8)) return "溢出";

    class Solution {
        public int myAtoi(String str) {
            if(str == null || str.length() == 0) return 0;
            int point = 0;
            boolean isPositive = true;
            int ans = 0;
    
            while (point < str.length() && str.charAt(point) == ' ') {
                point++;
            }
    
            if (point < str.length() && str.charAt(point) == '+') {
                point++;
            } else if (point < str.length() && str.charAt(point) == '-') {
                isPositive = false;
                point++;
            }
    
            while (point < str.length() && Character.isDigit(str.charAt(point))) {
                if (ans > Integer.MAX_VALUE / 10 ||
                        (ans == Integer.MAX_VALUE / 10 && str.charAt(point) - '0' > 7)) {
                    return isPositive ? Integer.MAX_VALUE : Integer.MIN_VALUE;
                }
    
                ans = ans * 10 + str.charAt(point++) - '0';
            }
    
            return isPositive ? ans : -ans;
        }
    }
    
  • DFA有限状态机

posted @ 2020-07-08 14:35  NLYang  阅读(176)  评论(0编辑  收藏  举报