classSolution{ privatebooleanis_num(char ch){ if((ch-'0'<=9)&&(ch-'0'>=0)) returntrue; returnfalse; } publicintmyAtoi(String str){ // str is empty if(str==null||str.length()==0) return0; // str contains only whitespace characters String newStr=str.trim(); if(newStr.length()==0) return0; // not a plus or minus sign or numerical digit at the head char ch=newStr.charAt(0); if(ch!='-'&&ch!='+'&&!is_num(ch)) return0; // only plus or minus sign if(ch=='-'&&newStr.length()==1||ch=='+'&&newStr.length()==1) return0; // multiple non-numberical digits except the plus and minus sign before integer numbers int count=0; while (count<newStr.length()&&!is_num(newStr.charAt(count))) { count++; } if(count>1) return0; boolean sign=true; StringBuilder sb=new StringBuilder(); if(newStr.charAt(0)=='-'){ sign=false; for(int i=1;i<newStr.length();i++){ if(is_num(newStr.charAt(i))) sb.append(newStr.charAt(i)); elsebreak; } } elseif(newStr.charAt(0)=='+'){ for(int i=1;i<newStr.length();i++){ if(is_num(newStr.charAt(i))) sb.append(newStr.charAt(i)); elsebreak; } } else { for(int i=0;i<newStr.length();i++){ if(is_num(newStr.charAt(i))) sb.append(newStr.charAt(i)); elsebreak; } } // e.g. "+0000" or "-0000" or "0000" while (sb.charAt(0)=='0') { sb.deleteCharAt(0); if(sb.length()==0) return0; } // if the number is too big, like bigger than maximum long integer. if(sign&&sb.length()>10) return Integer.MAX_VALUE; if(!sign&&sb.length()>10) return Integer.MIN_VALUE; // to check whether integer is within the 32-bit signed integer range: [−2^31, 2^31 − 1] if(!sign) return (0-Long.valueOf(sb.toString()))<=Integer.MIN_VALUE ?Integer.MIN_VALUE:0-Integer.valueOf(sb.toString()); return Long.valueOf(sb.toString())>=Integer.MAX_VALUE?Integer.MAX_VALUE:Integer.valueOf(sb.toString()); } }