您的位置:首页 > 其它

008_LeetCode_8 String to Integer (atoi) 题解

2017-11-20 14:17 561 查看

Description

Implement
atoi
to convert a string to an integer.

解:

此题需要注意的问题:

字符串中可能有空格

开头可能有正负号,且只能有一个符号,多于一个时为错误串

需要判断结果是否越界

java代码:

class Solution {
public int myAtoi(String str) {
if (str == null || str.length() < 1)
return 0;

// 消除空格
str = str.trim();

// 记录正负
boolean flag = true;

int i = 0;
if (str.charAt(0) == '-'){
flag = false;
i++;
}else if(str.charAt(0) == '+'){
i++;
}

double res = 0;
for (; i < str.length() && str.charAt(i) <= '9' && str.charAt(i) >= '0'; i++){
res = res * 10 + (str.charAt(i) - '0');
}

if (!flag)
res = -res;

if (res > Integer.MAX_VALUE)
return Integer.MAX_VALUE;

if (res < Integer.MIN_VALUE)
return Integer.MIN_VALUE;

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