您的位置:首页 > 其它

[LeetCode]--8. String to Integer (atoi)

2016-09-28 23:18 337 查看
Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

正如题目所说,真的是考虑各种情况。

public int myAtoi(String str) {
if (str == null || str.length() == 0)
return 0;
str = str.trim();
if (str.matches("([0-9]|-|\\+)[0-9]*")) {
if (str.charAt(0) == '+') {
if (str.length() > 11
|| str.length() == 1
|| (str.length() == 11 && !str
.matches("[+][1-2][0-1][0-4][0-7][0-4][0-8][0-3][0-6][0-4][0-7]")))
return 0;
else
return Integer.parseInt(str);
}
if (str.charAt(0) == '-') {
if (str.length() > 11
|| str.length() == 1
|| (str.length() == 11 && !str
.matches("[-][1-2][0-1][0-4][0-7][0-4][0-8][0-3][0-6][0-4][0-8]"))) {
return 0;
} else {
return Integer.parseInt(str);
}
}
if ((str.charAt(0) + "").matches("[0-9]")) {
if (str.length() > 10
|| (str.length() == 10 && !str
.matches("[1-2][0-1][0-4][0-7][0-4][0-8][0-3][0-6][0-4][0-7]")))
return 0;
else
return Integer.parseInt(str);
}
}
return 0;
}


上述程序是我第一次想出来的,基本情况都考虑进去了,还差一种情况没有考虑到:



下面这个就考虑到了所有情况,而且效率高很多。

public int myAtoi(String str) {
if (str == null)
return 0;
str = str.trim();
if (str.length() == 0)
return 0;
int index = 0;
int sign = 1;
if (str.charAt(index) == '+') {
sign = -1;
index++;
} else if (str.charAt(index) == '-')
index++;
long num = 0;
for (; index < str.length(); index++) {
System.out.println(str.charAt(index));
if (str.charAt(index) < '0' || str.charAt(index) > '9')
break;
num = num * 10 + (str.charAt(index) - '0');
if (num > Integer.MAX_VALUE)
break;
}
if (num * sign >= Integer.MAX_VALUE)
return Integer.MAX_VALUE;
if (num * sign <= Integer.MIN_VALUE)
return Integer.MIN_VALUE;
return (int) num * sign;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息