把字符串转化成整数

/**
 * @ClassName TestDemo67
 * @Description 面67
 * @Author lzq
 * @Date 2019/1/24 15:58
 * @Version 1.0
 **/
public class TestDemo67 {
    //非法输入,默认false(即没有非法输入)
    public boolean illegality = false;
    //数据溢出,默认false(即没有溢出)
    public boolean overflow = false;

    /**
     * 将字符串转化成整数的核心方法
     * @param str
     * @return
     */
    public int change(String str) {
        if(str == null || str.length() == 0) {
            illegality = true;  //非法输入
            return 0;
        }
        char[] chars = str.toCharArray();
        boolean symbol = true;  //符号,默认true(即默认'+'号,可以省略)
        int index = 0;  //字符数组下标
        /*
        sum用来保存字符串转化成的整数,要用long类型来保存,否则int型无法保存Integer.MAX_VALUE
        和Integer.MIN_VALUE,从而无法判断数据溢出
         */
        long sum = 0;     
        if(chars[index] == '-') {
            symbol = false; //负号,不能省略
            index++;
        }
        if(chars[index] == '+') {
            symbol = true;
            index++;
        }
        for(;index < str.length();index++) {
            if(chars[index] < '0' || chars[index] > '9') {
                illegality = true;  //非法输入
                return 0;
            }
            sum = sum*10+(chars[index]-'0');
            if(symbol && sum > Integer.MAX_VALUE || !symbol && sum > -Integer.MIN_VALUE) {
                sum = 0;
                overflow = true;  //数据溢出
                return 0;
            }
        }
        return symbol ? (int) sum : (int) sum*-1;
    }

    /**
     * 打印非法信息
     */
    public void show() {
        if(illegality) {
            System.out.println("非法输入!");
        }
        if(overflow) {
            System.out.println("数据溢出!");
        }
    }
}

你可能感兴趣的:(剑指offer编程题)