今天急急忙忙做了一个非常恶心的题目,说实话也不是说很恶心,只是我以前就没掌握怎么解决超出int型的数字表达方法,也不算表达方式吧,此处省略2W字对于自己能力不足的吐槽,直接列出题目:
我这道题陷入了魔咒,一直想只用Integer.parseInt,使用这个函数,虽然很简单,但是对于处理合理字符串就复杂了很多,因此我们转过来使用每个字符进行求解,无非是每次遍历时候都*10表示上一层的值!下面列出代码:
public int myAtoi(String str) {
char[] chars = str.toCharArray();
int n = chars.length;
int idx = 0;
while (idx < n && chars[idx] == ' ') {
// 去掉前导空格
idx++;
}
if (idx == n) {
//去掉前导空格以后到了末尾了
return 0;
}
boolean negative = false;
if (chars[idx] == '-') {
//遇到负号
negative = true;
idx++;
} else if (chars[idx] == '+') {
// 遇到正号
idx++;
} else if (!Character.isDigit(chars[idx])) {
// 其他符号
return 0;
}
int ans = 0;
while (idx < n && Character.isDigit(chars[idx])) {
int digit = chars[idx] - '0';
if (ans > (Integer.MAX_VALUE - digit) / 10) {
// 本来应该是 ans * 10 + digit > Integer.MAX_VALUE
// 但是 *10 和 + digit 都有可能越界,所有都移动到右边去就可以了。
return negative? Integer.MIN_VALUE : Integer.MAX_VALUE;
}
ans = ans * 10 + digit;
idx++;
}
return negative? -ans : ans;
}