您的位置:首页 > 其它

【Leetcode】8. String to Integer (atoi)

2016-12-11 21:42 393 查看
思路:

(1)去掉前后的空格。

(2)为防止溢出,result定义为long型,并定义flag标记正负数。

(2)依次判断每个字符,第一次遇到加号时,记flag为1;第一次遇到减号时,记flag为2;遇到数字时,存入result;否则直接break。

(3)若是负数,则需要result取反。

(4)若result超出最大正数,则返回Integer.MAX_VALUE;若result小于最小负数,则返回Integer.MIN_VALUE。

(5)强制转换后返回result。

public class Solution {
public int myAtoi(String str) {
str = str.trim();
long result = 0;
int flag = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (flag == 0 && str.charAt(i) == '+' )
flag = 1;
else if (flag == 0 && str.charAt(i) == '-')
flag = 2;
else if (str.charAt(i) >= '0' && ch <= '9') {
result = result * 10 + (ch - '0');
if (flag == 2 && result > Integer.MAX_VALUE)
return Integer.MIN_VALUE;
if (flag != 2 && result > Integer.MAX_VALUE)
return Integer.MAX_VALUE;
}
else
break;
}
if (flag == 2)
result = -result;
if (result > Integer.MAX_VALUE)
return Integer.MAX_VALUE;
if (result < Integer.MIN_VALUE)
return Integer.MIN_VALUE;
return (int)result;
}
}


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