字符串转整形--java

package test;

import java.awt.geom.FlatteningPathIterator;

/** * 字符串转换成整数,需要考虑几种情况: 是否会溢出;-2147483648,+2147483647 有没有非法字符,非数字; * * @author duola * */
public class StringToInt {

    private static int zhuanhuan(String s) {
        int n = 0;
        int max = Integer.MAX_VALUE;
        int min = Integer.MIN_VALUE;
        int flag = 1;
        if (s.length() == 0)
            return 0;
        char[] c = s.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == ' ') {
                i++;
                continue;
            }
            if (c[i] == '-')
                flag = -1;

            if (Character.isDigit(c[i])) {
                int a = c[i] - '0';
                if (flag == 1
                        && (n > max / 10 || (n == max / 10 && a > max % 10))) {
                    return max;
                }
                if (flag == -1
                        && (-n < min / 10 || (-n == min / 10 && -a < min % 10))) {
                    return min;
                }
                n = n * 10 + a;
            }
        }
        return flag > 0 ? n : -n;
    }

    public static void main(String[] args) {
        String string = "-21kk22";
        System.out.print(zhuanhuan(string));
    }
}

你可能感兴趣的:(字符串转整形--java)