题解 | #把字符串转换成整数(atoi)#
把字符串转换成整数(atoi)
http://www.nowcoder.com/practice/d11471c3bf2d40f38b66bb12785df47f
各种标识一点一点做出来的
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return int整型
*/
public int StrToInt (String s) {
// write code here
int ret = 0;
int flag = 1;
char[] chs = s.toCharArray();
int isFlag = 0;
int isNum = 0;
for(int i=0;i<chs.length;++i){
if(chs[i] == ' '){
if(isNum == 1) break;
if(isFlag == 1) break;
continue;
}
if((chs[i] >'9' || chs[i]<'0') && chs[i]!='-'
&& chs[i]!='+') break;
if(chs[i] == '-'){
if(isNum == 1) break;
if(isFlag == 1) break;
isFlag = 1;
if(flag == -1) break;
flag = -1;
continue;
}
if(chs[i] == '+'){
if(isNum == 1) break;
isFlag = 1;
if(flag == -1) break;
flag = 1;
continue;
}
int n = chs[i] - '0';
if(flag == 1 && ret > (Integer.MAX_VALUE-n)/10){
ret = Integer.MAX_VALUE;
break;
}
if(flag == -1 && -ret < (Integer.MIN_VALUE+n)/10){
ret = Integer.MIN_VALUE;
break;
}
ret = ret * 10 + n;
isNum = 1;
}
return flag * ret;
}
}