So this was the problem statement
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned.
Note:
Only the space character ' ' is considered as whitespace character.
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned.
and this is my solution that passes 1000+ tests and got accepted but it doesn't look good. could itrating the list with character comparison was a better idea?
public class Main {
public static int myAtoi(String str) {
if(str == null)
return 0;
str = str.trim();
if(str.matches(".*[A-Za-z0-9].*")){
String [] tokens = str.split("\\s+");
String s = tokens[0];
if(s.matches("[a-z]*\\D*")|| s.startsWith(".") ||s.matches("[+-]?[a-z]+\\d+") || s.matches("^[-+][+-][0-9]*"))
return 0;
if(s.matches("[+-]*[0-9a-z]*"))
s = s.split("[a-z]")[0];
if (s.matches("[+-]?([0-9]\\.?\\d*)")){
if(s.length() > 9){
Double num = Double.valueOf(s);
if(num > Double.valueOf(Integer.MAX_VALUE))
return Integer.MAX_VALUE;
if(num < Double.valueOf(Integer.MIN_VALUE))
return Integer.MIN_VALUE;
}
}
if(s.matches("[1-9]*[.][0-9]*")){
s = s.split("\\.",2)[0];
}if(s.matches("([-+]?[0-9]+[-+]+[0-9]+)")){
s=s.split("([-+][0-9]$)")[0];
}if(s.matches("^[-+][+-][0-9]*") ){
s = s.substring(2);
}if(s.matches("[-+]?(\\d+[-+]+)")){
s = s.split("[-+]+$")[0];
}if(s.matches("^[+][0-9]*")){
s = s.substring(1);
}
if(s.endsWith("-") ||s.endsWith("+"))
s=s.substring(0,s.length()-1);
if(s.endsWith("-+") ||s.endsWith("+-"))
s=s.substring(0,s.length()-2);
return Integer.valueOf(s);
}
return 0;
}
public static void main(String[] args) {
System.out.println("Hello World!");
String s1 = "42";
String s2 = " -42";
String s3 = "4193 with words";
String s4 = "words and 987";
String s5 = "91283472332";
String s6 = "3.145677";
String s7 = "-91283472332";
String s8 = "+1";
String s9 = "-+1";
String s10=" 0000000000012345678";
String s11=" -0012a42";
String s12="- 234";
String s13="-5-";
String s14=".1";
String s15="+-2";
String s16="0-1";
String s17="-1";
String s18="-13+8";
String s19="21474836++";
String s20=" +b12102370352";
System.out.println("returned="+ myAtoi(s20));
}
}