一开始想用正则表达式做,后来发现不用正则表达式更简单;本题是简单模拟;
题目大意就是给一个字符串,转化为int类型返回;
字符串可能以空字符开头,然后加上‘+’/‘-’或者直接数字,如果数字大于Max_Int或小于Min_Int则返回Max_Int或Min_Int
字符数字部分后可能有各种字符,忽略即可;
若字符串全为空之类的,或格式错误无法解析,返回0;
注意点:
- 数字可能大到超过Long类型
- +-2返回的是0
- start < length或者end < length放在判断的最前面
以下是代码:
class Solution{
public int myAtoi(String str) {
if (str == "") return 0;
int start = 0, end;
int c = 1, length = str.length();
while (start < length && (str.charAt(start) == ' ' || str.charAt(start) == '\n' || str.charAt(start) == '\r')) start++;
if (start == length) return 0;
if (str.charAt(start) == '-') {
c = -1;
start++;
} else if (str.charAt(start) == '+') start++;
end = start;
while (end < length && str.charAt(end) <= '9' && str.charAt(end) >= '0') end++;
if (end == start) return 0;
if (end - start > 10) {
if (c > 0) return Integer.MAX_VALUE;
return Integer.MIN_VALUE;
}
long result = Long.parseLong(str.substring(start,end));
result *= c;
if (result > Integer.MAX_VALUE) return Integer.MAX_VALUE;
if (result < Integer.MIN_VALUE) return Integer.MIN_VALUE;
return (int)result;
}
}