您的位置:首页 > 其它

8. String to Integer (atoi)(8.46%)

2016-01-13 18:05 225 查看
题目: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.

个人理解:实现atoi方法将字符串转为整数。这道题没什么把握,题目本身也没说太明白,只是提到要考虑很多种输入情况。比如,检测到一个整数字符的时候,接下来如果出现空格,那么就截止,将当前已检测到的整数返回。

public class Solution {
public int myAtoi(String str) {
int result = 0;

if (str == null || str.equals("")) {
return result;
}

char[] inputStrs = str.toCharArray();
String temp = "";
boolean canContinue = true;
boolean beginInput = false;
for (char c : inputStrs) {
if (c == ' ') {
if (!beginInput && canContinue) {
continue;
} else {
break;
}
} else if (c >= '0' && c <= '9') {
temp += c;
beginInput = true;
} else if (c == '-' || c == '+'){
if (canContinue) {
temp += c;
canContinue = false;
} else {
break;
}
} else {
break;
}

}

if (temp.equals("+") || temp.equals("-")) {
return 0;
}

if (temp.endsWith("+") || temp.endsWith("-")) {
return 0;
}

if (!temp.equals("")) {
try {
result = Integer.parseInt(temp);
} catch (Exception e) {
// TODO: handle exception
if (temp.contains("-")) {
return Integer.MIN_VALUE;
} else {
return Integer.MAX_VALUE;
}
}
}

return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: