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.
代码如下:
class Solution {
public:
long strtol(const char *nptr, char **endptr, int base)
{
const char * s;
long acc, cutoff;
int neg, any, cutlim;
int c;
if (base<0 || base==1 || base>36)
{
if (endptr!=0)
*endptr = (char*)nptr;
return 0;
}
s = nptr;
do
{
c = (unsigned char) *s++;
} while(isspace(c));
if (c == '-')
{
neg = 1;
c = *s++;
}
else
{
neg = 0;
if ( c=='+')
c = *s++;
}
if ((base==0 || base==16) &&c=='0' &&(*s =='x' || *s == 'X'))
{
c = s[1];
s+=2;
base = 16;
}
if (base == 0)
{
base = c=='0' ? 8:10;
}
cutoff = neg? LONG_MIN:LONG_MAX;
cutlim = cutoff %base;
cutoff /= base;
if (neg )
{
if (cutlim > 0)
{
cutlim -= base;
cutoff += 1;
}
cutlim = -cutlim;
}
for (acc =0, any=0;;c=(unsigned char)*s++)
{
if (isdigit(c))
c -= '0';
else if (isalpha(c))
c -= isupper(c) ? 'A'-10 : 'a'-10;
else
break;
if (c >= base)
break;
if(any < 0)
continue;
if (neg)
{
if (acc < cutoff || (acc==cutoff && c>cutlim))
{
any = -1;
acc = LONG_MIN;
}
else
{
any = 1;
acc *= base;
acc -= c;
}
}
else
{
if (acc>cutoff || (acc==cutoff && c>cutlim))
{
any = -1;
acc = LONG_MAX;
}
else
{
any = 1;
acc *= base;
acc += c;
}
}
}
if(endptr != 0)
*endptr = (char *)(any? s-1:nptr);
return acc;
}
int atoi(const char *str) {
return strtol(str, NULL, 10);
}
};