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.
Discussion
常规操作。注意一下特殊符号的处理即可。
算法的时间复杂度为O(n)。
C++ Code
class Solution {
public:
int myAtoi(string str) {
//空串返回0
if(str.length() == 0)
{
return 0;
}
//用一个long long类型的防止溢出
long long answer = 0;
//符号
int sign = 1;
int index = 0;
const int maxInt = 0x7fffffff;
const int minInt = 0x80000000;
//跳过空格
while(str[index] == ' ')
{
index++;
}
//记录符号,默认为正
if(str[index] == '+')
{
index++;
}
else if(str[index] == '-')
{
index++;
sign = -1;
}
//每次添加一位,并进行溢出判断。若遇到非数字字符,跳出并输出之前的数字。
for(int i = index; i < str.length(); i++)
{
if(str[i] >= '0' && str[i] <= '9')
{
answer = answer * 10 + str[i] - '0';
if(answer * sign > maxInt)
{
return maxInt;
}
if(answer * sign < minInt)
{
return minInt;
}
}
else
{
break;
}
}
answer = answer * sign;
return (int)answer;
}
};