[La espada se refiere a la oferta] 67. Convierte una cadena en un número entero

Descripción del Título

Inserte la descripción de la imagen aquí

// 牛客
// 将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 
// 数值为0或者字符串不是一个合法的数值则返回0

respuesta

// 牛客
// 牛客比力扣要简单(也更合理),出现其他字符统统不算int,直接返回0。
// 先排除特殊情况,初始化答案res=0。定义boolean值isNegative,
// 判断第一个字符是不是'-',最后返回答案时判断要不要负号。
// for循环遍历str字符,如果第一个字符是符号,跳过。
// 如果c小于0或大于9,直接返回0.
// 否则将当前c的值加到res,res之前的值乘10进位。遍历完,
// 字符回归它应该在的位数上。最后返回即可
// 运行时间:9ms,超过93.78%用Java提交的代码
// 占用内存:9656KB,超过70.77%用Java提交的代码
class Solution {
    public int strToInt(String str) {
        if (str == null || str.length() == 0)
			return 0;
		int res = 0;
		boolean isNegative = str.charAt(0) == '-';
		for (int i = 0; i < str.length(); i++) {
			char c = str.charAt(i);
			if (i == 0 && (c == '+' || c == '-'))
				continue;
			if (c < '0' || c > '9')
				return 0;
			res = res * 10 + (c - '0');
		}
		return isNegative ? -res : res;
    }
}

Supongo que te gusta

Origin blog.csdn.net/fisherish/article/details/115033679
Recomendado
Clasificación