LeetCode#p8-字符串转换整数
package zifuchuan;
public class p8 {
//未全过 1074/1079
/*public static int myAtoi(String str) {
if(str==null||str.length()==0)return 0;
String s="+-0123456789";
StringBuilder sb=new StringBuilder();
int i=0;
for(;i<str.length();i++){
if(str.charAt(i)!=' ')break;
}
for(;i<str.length();i++){
if(s.indexOf(str.charAt(i))==-1)break;
else {
sb.append(str.charAt(i));
}
}
try {
if(sb.toString()==null||sb.toString().length()==0)return 0;
return Integer.valueOf(sb.toString());
}catch (Exception e){
if(sb.toString().charAt(0)=='-'&&sb.toString().length()>=11)return Integer.MIN_VALUE;
else if(sb.toString().charAt(0)=='+'&&sb.toString().length()>=11) return Integer.MAX_VALUE;
else if(sb.toString().charAt(0)<=9+'0'&&sb.toString().charAt(0)>=0+'0'&&sb.toString().length()>=10)return Integer.MAX_VALUE;
}
return 0;
}*/
public static int myAtoi(String str) {
if(str==null||str.length()==0)return 0;
String s="0123456789";
StringBuilder sb=new StringBuilder();
int i=0;
for(;i<str.length();i++){
if(str.charAt(i)!=' ')break;
}
boolean flag=false;
if(i==str.length())return 0;
if(str.charAt(i)=='-'){
flag=true;
i++;
}
else if(str.charAt(i)=='+'){
i++;
}
//System.out.println(flag);
if(i==str.length())return 0;
if(str.charAt(i)!='-'&&s.indexOf(str.charAt(i))==-1)return 0;
//System.out.println("--------");
for(;i<str.length();i++){
if(s.indexOf(str.charAt(i))==-1)break;
else {
sb.append(str.charAt(i));
}
}
//System.out.println(sb.toString());
//System.out.println("--------");
try {
if(sb.toString()==null||sb.toString().length()==0)return 0;
//System.out.println("ennen");
if(flag==true)return -Integer.valueOf(sb.toString());
else return Integer.valueOf(sb.toString());
}catch (Exception e){
//System.out.println("falg-----:"+flag);
if(flag==true){
//System.out.println("hahaha");
return Integer.MIN_VALUE;
}
else return Integer.MAX_VALUE;
}
}
public static void main(String[] args) {
String s="2147483648";
System.out.println(myAtoi(s));
}
}
运行结果:


浙公网安备 33010602011771号