您的位置:首页 > 其它

LeetCode(8)--String to Integer (atoi)

2015-12-03 21:58 417 查看
题目如下:

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.

解题思路:

首先,要判断该字符串是否可以还换成int类型,然后,判断字符的符号(测试集中有-和+),最后将字符传中的数逐个取出即可。

提交的代码:

public int myAtoi(String str) {
int p = 0, ret = 0;
while(p < str.length() && Character.isWhitespace(str.charAt(p))) ++p;
if(p == str.length()) return 0;
boolean negFlag = (str.charAt(p) == '-');
if(str.charAt(p) == '+'  || str.charAt(p) == '-') ++p;
for(; p<str.length(); ++p) {
if(str.charAt(p) > '9' || str.charAt(p) < '0') {
break;
}else {
int digit = str.charAt(p) - '0';
if(!negFlag && ret > (Integer.MAX_VALUE - digit) /10)
return Integer.MAX_VALUE;
else if(negFlag && ret < (Integer.MIN_VALUE + digit)/10)
return Integer.MIN_VALUE;
ret = ret * 10 + (negFlag? -digit: digit);
}
}
return ret;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: