给定字符串,将其转成整数。
字符串中可能有前导空格,+,-,数字,大小写字母,空格。
字符串长度最大是200,如果超出32位有符号数直接返回32位有符号数边界。
示例:
" 123" -> 123
"123 abs" -> 123
"jingn 123" -> 0
"124567657776776" -> 2147483647
class Solution {
public int myAtoi(String s) {
int i = 0;
while (i < s.length() && s.charAt(i) == ' ') i ++;
if (i == s.length()) return 0;
if (s.charAt(i) == '+' || Character.isDigit(s.charAt(i))) {
long ans = 0;
if (s.charAt(i) == '+') i ++;
while (i < s.length() && Character.isDigit(s.charAt(i))) {
ans = ans * 10 + s.charAt(i) - '0';
if (ans > Integer.MAX_VALUE) return Integer.MAX_VALUE;
i ++;
}
return (int) ans;
}
else if (s.charAt(i) == '-') {
long ans = 0;
i++;
while (i < s.length() && Character.isDigit(s.charAt(i))) {
ans = ans * 10 + s.charAt(i) - '0';
if (-1 * ans < Integer.MIN_VALUE) return Integer.MIN_VALUE;
i++;
}
return (int) (-1 * ans);
}
else {
return 0;
}
}
}