您的位置:首页 > 其它

[LeetCode 解题报告]008.String to Integer (atoi)

2017-05-25 21:32 363 查看
Description:

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.

Update (2015-02-10):

The signature of the 
C++
 function had been updated. If you still see your function signature
accepts a 
const char *
 argument, please click the reload button  to
reset your code definition.

spoilers alert... click to show requirements for atoi.
注意Case点:

该字符串前边可能有若干空格(用#表示空格)“###010”返回值应为10
去除前边的若干个空格之后,需考虑接下来的一个字符是‘+‘还是’-’
碰到非数字字符结束
转换成数字时候需考虑是否产生越界

class Solution {
public:
int myAtoi(string str) {

if(str.length() == 0)
return 0;

int i = 0, sign = 1, res = 0;
while(isspace(str[i]))
i ++;

if(str[i] == '+' || str[i] == '-') {
if(str[i] == '-')
sign = 0;
i ++;
}

str = str.substr(i);

for(int j = 0; j < str.length(); j ++) {
if(!isdigit(str[j])) {
str = str.substr(0, j);
break;
}
}

if(str.length() == 0)
return 0;
for(int i = 0; i < str.length(); i ++) {

int c = (str[i] - '0');

if(sign == 1 && (res > INT_MAX / 10 || res == INT_MAX / 10 && c > INT_MAX % 10))
{
return INT_MAX;
}
else if(sign == 0 && (res > INT_MAX / 10) || res == INT_MAX / 10 && c > (INT_MAX % 10 + 1))
{
return INT_MIN;
}
res = res * 10 + c;

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