您的位置:首页 > 其它

个人记录-LeetCode 8.String to Integer (atoi)

2016-10-01 17:35 330 查看
问题

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 class Solution {
public int myAtoi(String str) {
if (str == null) {
return 0;
}

char[] sChar = str.toCharArray();
int len  = sChar.length;
if (len <= 0) {
return 0;
}

int beginIndex = 0;
//跳过空格
for (int i = 0; i < len; ++i) {
if (sChar[i] == ' ') {
++beginIndex;
} else {
break;
}
}

boolean negative = false;
//判断是否以+、-号开头
if (sChar[beginIndex] == '-') {
negative = true;
++beginIndex;
} else if (sChar[beginIndex] == '+') {
++beginIndex;
}

long result = 0;
for (int i = beginIndex; i < len; ++i) {
int temp = sChar[i] - '0';
//判断是否为数字,不是的话则结束解析
if (temp >=0 && temp <=9) {
result = result * 10 + temp;

if (result > Integer.MAX_VALUE) {
if (negative) {
return Integer.MIN_VALUE;
} else {
return Integer.MAX_VALUE;
}
}
} else {
break;
}
}

if (negative) {
result *= -1;
}

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