力扣刷题日记-8. 字符串转换整数 (atoi)

55 阅读1分钟
  • 最吐血的一道题了.调了好久才通过.大无语,脑袋都晕了💫😵‍💫
  • 感觉也没有什么特别的高深的算法技巧吧,就是不断调试不断调试.
  • 下午睡了一觉,起来被这题折腾累了,今天就到这了.😵‍💫😵‍💫😵‍💫😵‍💫😵‍💫
class Solution {
    public int myAtoi(String s) {
        if(s == null || s.equals("")) {
            return 0;
        }
        s = removeHeadZero(s.trim());
        if(s == null || s.equals("")) {
            return 0;
        }
        char[] str = s.toCharArray();
        if(!isValid(str)) {
            return 0;
        }
        boolean posi = str[0] == '-' ? false : true;
        int minq = Integer.MIN_VALUE / 10;
        int minr = Integer.MIN_VALUE % 10;
        int res = 0;
        int cur = 0;
        for(int i = (str[0] == '-' || str[0] == '+') ? 1 : 0; i < str.length; i++) {
            cur = '0' - str[i];
            if((res < minq) || (res == minq && cur < minr)) {
                return posi ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            }
            res = res * 10 + cur;
        }
        if(posi && res == Integer.MIN_VALUE) {
            return Integer.MAX_VALUE;
        }
        return posi ? -res : res;
        
    }
    public static String removeHeadZero(String str) {
        boolean r = (str.startsWith("+") || str.startsWith("-"));
        int s = r ? 1 : 0;
        for(;s < str.length();s++) {
            if(str.charAt(s) != '0') {
                break;
            }
        }// s 到了第一个不是0字符的位置
        int e = -1;
        for(int i = str.length() - 1; i >= (r ? 1 : 0); i--) {
            if(str.charAt(i) < '0' || str.charAt(i) > '9') {
                e = i;
            }
        }// e 到了最左的 不是数字字符的位置
        return (r ? String.valueOf(str.charAt(0)) : "") + str.substring(s,e == -1 ? str.length() : e);
    }
    public static boolean isValid(char[] chas){
        if(chas[0] != '-' && chas[0] != '+' && (chas[0] < '0' || chas[0] > '9')){
            return false;
        }
        if((chas[0] == '-' || chas[0] == '+') && chas.length == 1) {
            return false;
        }
        for(int i = 1; i < chas.length;i++) {
            if(chas[i] < '0' || chas[i] > '9') {
                return false;
            }
        }
        return true;
    }
}