Sword se refiere a offer-49- convierte una cadena en un entero-java

Preguntas y pruebas

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


public class main {
	
	public static void main(String[] args) {
		String [] testTable = {"123","+12","-569","+12345678901556","-2147483648","-2147483649","2147483647","2147483648","1a"};
		for (String ito : testTable) {
			test(ito);
		}
	}
		 
	private static void test(String ito) {
		Solution solution = new Solution();
		int rtn;
		long begin = System.currentTimeMillis();
		System.out.print(ito);		    
		System.out.println();
		//开始时打印数组
		rtn= solution.strToInt(ito);//执行程序
		long end = System.currentTimeMillis();	
		
		System.out.println("rtn=" );
		System.out.print(rtn);
		System.out.println();
		System.out.println("耗时:" + (end - begin) + "ms");
		System.out.println("-------------------");
	}

}

Solución 1 (éxito)

Preste atención a la legalidad de los datos de entrada, como "1234 + 12", "12 @@ # * 24", estos son todos valores ilegales y se debe devolver 0. Pero si el primer carácter es + o - y afecta al último símbolo de salida, es necesario juzgar si el número está fuera de rango al final.

Al calcular, primero convierta el número en un número negativo. El rango de int es [-2147483648,2147483647], y se puede calcular el número negativo más pequeño.

package sword049;


public class Solution {
	public int strToInt(String s) {
		int length = s.length();
		int index = 0;
		boolean isPositive = true;
		if(s.charAt(index) == '+') {
			index++;
		}
		if(s.charAt(index) == '-') {
			index++;
			isPositive = false;
		}
		int num = 0;
		while(index<length) {
			int now = s.charAt(index) - '0';
			if(now < 0 || now > 9) {
				return 0;
			}
			if(num < -214748364 ) {
				return 0;
			}
			if(num == -214748364 ) {
				if(isPositive) {
					if(now > 7) {
						return 0;
					}
				}else {
					if(now > 8) {
						return 0;
					}
				}
			}
			num = 10 * num - now;
			index++;
		}
		if(isPositive) {
			num = -num;
		}

		return num;
	}

}

 

Supongo que te gusta

Origin blog.csdn.net/xushiyu1996818/article/details/112555118
Recomendado
Clasificación