将整数字符串转成整数值

该博客主要讨论如何将符合日常书写习惯且在32位整数范围内的字符串转换为对应的整数值。例如,字符串'123'能成功转换为整数123,而'023'因不符合书写习惯、'A13'因包含非数字字符、'2147473648'因超出32位整数范围则无法转换,返回0。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【题目】给定一个字符串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;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值