![](/img/trans.png)
[英]Implementing my own LinkedList, insertion of a new element to the Tail doesn't work correctly
[英]my own String to Integer (atoi) function doesn't work correctly
我的代码可以解释前导空格和非数字字符。 它失败了第四和第五种情况。 输入:s = "words and 987" 和输入:s = "-91283472332" 案例。 我不确定如何解释这些情况。
class Solution {
public int myAtoi(String s) {
int length = s.length();
boolean pos = true;
int i = 0, num = 0;
if(s.length() == 0) {
return 0;
}
while(s.charAt(i) == ' ') {
i++;
}
if(s.charAt(i) == '-') {
pos = false;
i++;
}
else if(s.charAt(i) == '+') {
pos = true;
i++;
}
while(i < length) {
if(Character.isDigit(s.charAt(i))) {
num = (num * 10) + Character.getNumericValue(s.charAt(i));
}
i++;
}
if(!pos) {
num *= -1;
}
if(num < Integer.MIN_VALUE) {
num = Integer.MIN_VALUE;
}
else if(num > Integer.MAX_VALUE) {
num = Integer.MAX_VALUE;
}
return num;
}
}
public static int myAtoi(String str) {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (buf.length() == 0) {
if (ch == '-' || ch == '+' || (ch >= '0' && ch <= '9'))
buf.append(ch);
else if (ch != ' ')
return 0;
} else if (ch < '0' || ch > '9')
break;
else
buf.append(ch);
}
try {
BigDecimal res = new BigDecimal(buf.toString());
if (res.compareTo(BigDecimal.valueOf(Integer.MAX_VALUE)) > 0)
return Integer.MAX_VALUE;
if (res.compareTo(BigDecimal.valueOf(Integer.MIN_VALUE)) < 0)
return Integer.MIN_VALUE;
return res.intValue();
} catch(Exception e) {
return 0;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.