Java 中 实现atoi将字符串转换为整数。

分析

对于此问题,应考虑以下情况:

1. null or empty string
2. white spaces
3. +/- sign
4. calculate real value
5. handle min & max

Java解决方案

public int atoi(String str) {
	if (str == null || str.length() < 1)
		return 0;
 
	//修剪空白 
	str = str.trim();
 
	char flag = '+';
 
	//检查负数或正数
	int i = 0;
	if (str.charAt(0) == '-') {
		flag = '-';
		i++;
	} else if (str.charAt(0) == '+') {
		i++;
	}
	//使用double存储结果
	double result = 0;
 
	//计算值
	while (str.length() > i && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
		result = result * 10 + (str.charAt(i) - '0');
		i++;
	}
 
	if (flag == '-')
		result = -result;
 
	//手柄最大值和最小值
	if (result > Integer.MAX_VALUE)
		return Integer.MAX_VALUE;
 
	if (result < Integer.MIN_VALUE)
		return Integer.MIN_VALUE;
 
	return (int) result;
}

在这里插入图片描述

原创文章 115 获赞 0 访问量 2972

猜你喜欢

转载自blog.csdn.net/qq_41806546/article/details/105594546