public class Solution008 {
public int myAtoi(String str) {
if (str == null)
return 0;
str = str.trim();
if ("".equals(str))
return 0;
StringBuilder sb = new StringBuilder();
int sign = 1;
if (str.startsWith("+")) {
str = str.replaceFirst("\\+", "");
} else if (str.startsWith("-")) {
sign = -1;
str = str.replaceFirst("-", "");
}
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c > '9' || c < '0') {
break;
}
sb.append(c);
}
try {
long l = sign * Long.parseLong(sb.toString());
if (l >= Integer.MAX_VALUE)
return Integer.MAX_VALUE;
if (l <= Integer.MIN_VALUE)
return Integer.MIN_VALUE;
return (int) (l);
} catch (Exception e) {
return 0;
}
}
public static void main(String[] args) {
System.out.println(Integer.MIN_VALUE);
System.out.println(Integer.MAX_VALUE);
Solution008 s8 = new Solution008();
String strs[] = {
"", "-2147483648", "-2147483649", "2147483648", "-2147483648",
"1010023630", "-1010023630",
" 10522545459", " 10522545459+123 ",
"-123", "+123", " -123 ", "+123sdf",
"11111111111111111111111111111111111111111111111111",
"sfjdk", "-fjdks", "+fjsdk" };
for (String s : strs) {
System.out.println(s + "-->" + s8.myAtoi(s));
}
}
}