public class Solution {
public int atoi(String str) {
str = str.trim();
if(str.matches("(\\+?|-?)\\d+.*")) {
boolean isPos = true;
if(str.charAt(0) == '-') {
isPos = false;
}
String s = str.replaceAll("(\\++|-+)", " ").trim().split("\\D+")[0];
double num = 0; // The precision of float is not accurate
for(int i = 0; i < s.length(); i++) {
num = 10 * num + s.charAt(i) - '0';
}
num = isPos ? num : -num;
if(num > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
if(num < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
return (int)num;
}
return 0;
}
}
Time: O(n)
Space: O(1)