Sword refers to offer-49- convert a string to an integer-java

Questions and tests

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("-------------------");
	}

}

Solution 1 (success)

Pay attention to the legality of the input data, such as "1234+12", "12@@#*24", these are all illegal values, and 0 should be returned. But if the first character is + or -, and it affects the last output symbol, it is necessary to judge whether the number is out of range at the end.

When calculating, first turn the number into a negative number. The range of int is [-2147483648,2147483647], and the smallest negative number can be calculated.

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;
	}

}

 

Guess you like

Origin blog.csdn.net/xushiyu1996818/article/details/112555118