int atoi ( const char * str );
This is how it did:
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus orminus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
We only need to consider to convert "19" into 19. No need to consider whitespace
int myatoi(const char *str)
{
int i = 0;
while(*str)
{
i = i << 3 + i << 1 + (*str - '0');
str++;
}
return 0;
}
There is also one easy way to do this:
ReplyDeleteint myatoi(const char *str)
{
int value = 0;
while(*str && *str <= '9' && *str >= '0')
{
value = value * 10 + (*str - '0');
str++;
}
return value;
}