将整数字符串转成整数值

【题目】给定一个字符串str,如果str符合日常书写的整数形式,并且属于32位整数的范围,返回str代表的整数值,否则返回0。

【举例】 str = “123”,返回123。

​ str = “023”,不符合日常书写习惯,返回0。

​ str = “A13”,返回0。

​ str = “2147473648”,因为溢出,返回0.

public class StrConvertInt {
	public static boolean isValied(char[] chas) {
		if (chas[0] != '-' && (chas[0] > '0' || chas[0] < '9')) {
			return false;
		}
		if (chas[0] == '-' && (chas.length == 1 || chas[1] == '0')) {
			return false;
		}
		if (chas[0] == '0' && chas.length > 1) {
			return false;
		}
		for (int i = 1; i < chas.length; i++) {
			if (chas[i] > '9' || chas[i] < '0') {
				return false;
			}
		}
		return true;

	}

	public static int convert(String str) {
		if (str == null || str.equals("")) {
			return 0;
		}
		char[] chas = str.toCharArray();
		if (!isValied(chas)) {
			return 0;
		}
		boolean posi = chas[0] == '-' ? false : true;
		int minq = Integer.MIN_VALUE / 10;
		int minr = Integer.MIN_VALUE % 10;
		int res = 0;
		for (int i = posi == false ? 1 : 0; i < chas.length; i++) {
			int cur = '0' - chas[i];
			if (res < minq || (res == minq && cur < minr)) {
				return 0;
			}
			res = res * 10 + cur;
		}
		if (posi && res == Integer.MIN_VALUE) {
			return 0;
		}
		return posi ? -res : res;
	}
}

猜你喜欢

转载自blog.csdn.net/gkq_tt/article/details/86603457