97 将整数字符串转成整数值
Table of Contents

ac

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
    public static Scanner sc = new Scanner(System.in);

    public static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    public static void main(String[] args) throws Exception {
        String s = sc.next();
        System.out.println(str2int(s));
    }

    static int str2int(String s){
        if(s == null || s.isEmpty()){
            return 0;
        }
        int n = s.length();
        int index = 0;
        boolean flag = true;
        if(s.charAt(0) == '-'){
            flag = false;
            index++;
        }
        if(n == index){
            return 0;
        }
        // 有其它字符返回0
        for(int i=index;i<n;i++) {
            char c = s.charAt(i);
            if (c < '0' || c > '9') {
                return 0;
            }
        }
        // 首位字符是0
        if(s.charAt(index) == '0'){
            return 0;
        }
        // [-2147483648, 2147483647]
        int maxLen = 10;
        if(n - index < maxLen){ // 小于10位数,直接求即可
            int sum = 0;
            for(int i=index;i<n;i++) {
                int val = s.charAt(i) - '0';
                sum = sum * 10 + val;
            }
            return flag ? sum : -sum;
        }else if(n - index > maxLen){ // 超出范围
            return 0;
        }else {
            // 10位
            int[] maxVal = {2, 1, 4, 7, 4, 8, 3, 6, 4, 7};
            if(!flag){
                maxVal[maxLen - 1] = 8;
            }
            int sum = 0;
            int maxIndex = 0;
            for(int i=index;i<n;i++){
                int val = s.charAt(i) - '0';
                if(val > maxVal[maxIndex ++]){
                    return 0;
                }
                sum = sum * 10 + val;
            }
            return flag ? sum : -sum;
        }
    }


}
/*
123
123

023
0

A13
0

2147483647
2147483647

2147483648
0

-127
-127
 */