Saturday, October 8, 2011

Two implementations of atoi function in C

Recursive implementation:
int atoi(char* str)
{
    if (!str) return 0;
    return (str[0]-'0')*pow(10,len(str)-1)+atoi(str+1);
}
int atoi(char* str)
{
    int result = 0;
    while(str)
    {
        result += (str[0]-'0')*pow(10,len(str)-1);
        str++;
    }
    return result;
}

No comments:

Post a Comment