1 package myAtoi8; 2 /* 3 * Implement atoi to convert a string to an integer. 4 Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases. 5 Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front. 6 Update (2015-02-10): 7 The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition. 8 */ 9 10 public class Solution {11 public static int myAtoi(String str) {12 StringBuilder sb=new StringBuilder();13 int flag=0;14 if(str.length()==0)15 return 0;16 else{17 for(int i=0;i'9')19 if(str.charAt(i)=='0'||str.charAt(i)==' ')20 if (sb.length()==0)21 continue;22 else23 break;24 else if (str.charAt(i)=='-')25 if (flag==0){26 flag=-1;27 sb.append('0');28 }29 else30 break;31 else if (str.charAt(i)=='+')32 if (flag==0){33 flag=1;34 sb.append('0');35 }36 else37 break;38 else39 break;40 else41 sb.append(str.charAt(i)); 42 } 43 }44 if(sb.length()==0)45 return 0;46 else if(sb.length()>12)47 str=sb.substring(sb.length()-12);48 else49 str=sb.toString();50 if (flag==-1)51 str="-"+str;52 long result=Long.parseLong(str);53 System.out.println(result);54 if (result>2147483647)55 return 2147483647;56 else if (result<-2147483648)57 return -2147483648;58 else59 return (int)result;60 61 }62 public static void main(String[] args){63 String str1="";//064 String str2="+";//065 String str3=" +45555";//4555566 String str4=" -45555";//-4555567 String str5="2147483647";//214748364768 String str6="2147483648";//214748364769 String str7="+-2";//070 String str8="-+2";//071 String str9="++2";//072 String str10="-2147483648";//-214748364873 String str11=" - 321";//074 String str12=" -11919730356x";//-214748364875 String str13="1234567890123456789012345678901234567890";//214748364776 System.out.println(myAtoi(str1));77 System.out.println(myAtoi(str2));78 System.out.println(myAtoi(str3));79 System.out.println(myAtoi(str4));80 System.out.println(myAtoi(str5));81 System.out.println(myAtoi(str6));82 System.out.println(myAtoi(str7));83 System.out.println(myAtoi(str8));84 System.out.println(myAtoi(str9));85 System.out.println(myAtoi(str10));86 System.out.println(myAtoi(str11));87 System.out.println(myAtoi(str12));88 System.out.println(myAtoi(str13));89 90 91 }92 }