public class Main {
public static void main(String[] args) {
String str = "123";
int help = help(str);
System.out.println(help);
}
public static int help(String str){
if (str==null||str.length()==0){
return 0;
}
long res = 0;
boolean negative = false;
int i=0;
str = str.trim();
char first = str.charAt(0);
if (first=='-'){
negative=true;
i++;
}else if (first=='+'){
i++;
}
while (i<str.length()){
char ch = str.charAt(i);
if (ch<'0'||ch>'9'){
return negative?-(int) res:(int) res;
}
int dig = str.charAt(i++)-'0';
res = res*10+dig;
if (negative==false&&res>Integer.MAX_VALUE){
return Integer.MAX_VALUE;
}
if (negative==true&&res-1>Integer.MAX_VALUE){
return Integer.MAX_VALUE;
}
}
return negative?-(int)res:(int)res;
}
}
字符串转数字
最新推荐文章于 2022-08-17 18:08:49 发布