代码重构: leetcode 8. 字符串转换整数 (atoi)

139 阅读1分钟

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

其实就是模拟一下。

但值得注意的是,我们在判断溢出时候,以及在判断是否符合情况,如何做到逻辑的简化和代码的书写。

我们的逻辑规划:

  1. 判断第一个是否是符号,然后标记正负,阅读index若有正负号,从下一个开始
  2. 因为有前导零,从index去除前导零,也就是更新index
  3. 从真正的数据域开始读,如果非数字则停止,否则加入记录,判断越界情况
    public int myAtoi(String s) {
        long ans = 0;
        s = s.trim();
        if (s.length() == 0) return 0;
        int index = 0;
        boolean isNeg = s.charAt(0) == '-';
        if (s.charAt(0) == '+' || s.charAt(0) == '-') index++;
        while (index < s.length() && s.charAt(index) == '0') index++;
        for (; index < s.length(); index++) {
            if (s.charAt(index) < '0' || s.charAt(index) > '9') break;
            ans = ans * 10 + s.charAt(index) - '0';
            if (isNeg && -ans < Integer.MIN_VALUE) return Integer.MIN_VALUE;
            else if(!isNeg && ans > Integer.MAX_VALUE) return Integer.MAX_VALUE;
        }
        ans = isNeg ? -ans : ans;
        return (int) ans;
    }