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.
Note:
这是参照别人的代码写的!原理很简单,就是得注意实现过程的各个细节!!
Code:
class Solution {
public:
int atoi(const char *str)
{
assert(str!=NULL);
while(isspace(*str))
str++;
int sign=*str=='-'?-1:1;
if(*str=='-' || *str=='+')
str++;
int ret=0;
while(isdigit(*str))
{
int digit=*str-'0';
if(INT_MAX/10>=ret)
ret*=10;
else
return sign==-1?INT_MIN:INT_MAX;
if(INT_MAX-digit>=ret)
ret+=digit;
else
return sign==-1?INT_MIN:INT_MAX;
str++;
}
return ret*sign;
}
};