天天看点

字符串转整数(atoi)

 /*字符串题一般考查的都是边界条件、特殊情况的处理。所以遇到此题一定要问清楚各种条件下的输入输出应该是什么样的。这里已知的特殊情况有:

能够排除首部的空格,从第一个非空字符开始计算

允许数字以正负号(+-)开头

遇到非法字符便停止转换,返回当前已经转换的值,如果开头就是非法字符则返回0

在转换结果溢出时返回特定值,这里是最大/最小整数

public int myAtoi_2(String str) {
		 if (str.isEmpty()) 
			 return 0;
	     int sign = 1, i = 0, n = str.length();
	     long base = 0;
	     while (i < n && str.charAt(i) == ' ') 
	    	 ++i;
	     if (str.charAt(i) == '+' || str.charAt(i) == '-') {
	         sign = (str.charAt(i++) == '+') ? 1 : -1;
	     }
	     while (i < n && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
	        base = 10 * base + (str.charAt(i) - '0');
	        if (base > Integer.MAX_VALUE  ||  base < Integer.MIN_VALUE) {
	            return (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
	        }
	        i++;
	     }
	    return (int)base * sign;
           

继续阅读