public class Solution {
public int StrToInt(String str) {
if(str.length() == 0)return 0;
String fuhao = str.substring(0,1);
Boolean isPositive = false;
if(fuhao.equals("+")){
str = str.substring(1);
isPositive= true;
}else if(fuhao.equals("-")){
str = str.substring(1);
}else{
fuhao="+";
isPositive= true;
}
char[] chars = str.toCharArray();
int index= 0;
int a = 0;
while(index < chars.length){
if(isNum(chars[index])){
a= a*10+(chars[index++] - '0');
if (isPositive && a > Integer.MAX_VALUE) {
a = Integer.MAX_VALUE;
break; //因为此处以为最大值,所以直接break
}
if (!isPositive && -a <( 1 + Integer.MAX_VALUE)) {
a = 1 + Integer.MAX_VALUE;
break;
}
}else{
return 0;
}
}
return isPositive?a:-a;
}
public boolean isNum(char c){
return c>='0' && c<='9';
}
}
把字符串转换成整数
最新推荐文章于 2022-01-12 10:18:48 发布