您的位置:首页 > 其它

LeetCode OJ8 String to Integer (atoi) 小结

2015-09-23 10:20 381 查看

String to Integer (atoi)

题目描述

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.


解题思路

这道题目的处理思路主要是, 提取字符串中的 首个’-‘, ‘+’ 字符, 以及相应的数字, 并且, 需要考虑溢出的问题

my code

class Solution {
public:
int myAtoi(string str) {
int len = str.size();
bool start = false;
bool isNeg = false;
bool isInValid = false;
long convertNum = 0;

for (int i = 0; i != len; i++)
{
if (str[i] == ' ' && start == false)
continue;

if (str[i] == '+' && start == false)
{
start = true;
continue;
}

if (str[i] == '-' && start == false)
{
start = true;
isNeg = true;
continue;
}

if (str[i] < '0' || str[i] > '9')
{
isInValid = true;
break;
}

convertNum = 10 * convertNum + str[i] - '0';
start = true;

if (convertNum > INT_MAX)
break;
}

convertNum = isNeg ? -1 * convertNum : convertNum;

// overflow detection
if (convertNum >= INT_MAX || convertNum <= INT_MIN)
convertNum = isNeg ? INT_MIN : INT_MAX;

return convertNum;
}
};


大神的代码

demo1

感觉好像外层的for 没有任何的意义

使用find_first_not_of 简化流程

int myAtoi(string str) {
long result = 0;
int indicator = 1;
for(int i = 0; i<str.size();)
{
i = str.find_first_not_of(' ');
if(str[i] == '-' || str[i] == '+')
indicator = (str[i++] == '-')? -1 : 1;
while('0'<= str[i] && str[i] <= '9')
{
result = result*10 + (str[i++]-'0');
if(result*indicator >= INT_MAX) return INT_MAX;
if(result*indicator <= INT_MIN) return INT_MIN;
}
return result*indicator;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: