I will show you my problem. This is using leetcode and I'm trying to create an atoi method.
public int myAtoi(String s) {
System.out.println(s.matches("^[^ -0123456789].*")); //this is the regex I am debugging
if(s.matches("^[^ -0123456789].*")){
return 0;
}
int solution = 0;
s = s.replaceAll("[^-0123456789.]","");
solution = 0;
boolean negative = false;
if(s.charAt(0) == '-'){
s = s.replaceAll("-","");
negative = true;
}
if(s.matches("^[0-9]?[.][0-9]+")){
s = s.substring(0, s.indexOf('.'));
System.out.println(s);
}
for(int i = s.length(); i > 0; i--){
solution = solution + (s.charAt(s.length() - i) - 48) * (int)Math.pow(10,i - 1);
}
if(negative) solution = solution * -1;
if(negative && solution > 0) return (int) Math.pow(-2,31);
if(!negative && solution < 0) return (int) Math.pow(2,31) - 1;
return solution;
}
here is the output section screenshot provided incase I have missed something there but a text description also exists.
When the input is "+-12" the output is supposed to be (int) 0. This is due to the requirement being that "if the string does not start with a number, a space, or a negative sign" we return 0.
The line of code whch is supposed to handle this starts at 4 and looks like
if(s.matches("^[^ -0123456789].*")){
return 0;
}
What is wrong with my regex?