Simple Programming Exercises, Part II

May 30, 2006

Here are some more simple programming exercises:

I got these ideas from Joel Spolsky's article on conducting job interviews. As with before, I solved both problems with a pen and paper, since that's what I'd have in a real job interview.

Here is my implementation of atoi(3):

int atoi(char* str)
{
    int last;
    int sign = 1;
    int ret_val = 0;
    int i;

    if ('-' == *str)
    {
            sign = -1;
            str++;
    }

    last = strlen(str) - 1;
    for (i=0; i< =last; i++)
    {
            ret_val += (str[i] - 48) * 
            (int)pow(10.0, last - i);
    }
    return sign * ret_val;
}

The next function implements itoa(). There is no itoa() in the standard C library, and Spolsky didn't provide the function prototype in his article, so I'm implementing the function described on cplusplus.com's reference page. Here's the code:

void itoa(int n, char* str, int radix)
{
    char* chars = "0123456789ABCDEF";
    short negative = 0;
    char* ptr = str;
    char tmp;

    if (n < 0)
    {
        negative = 1;
        n *= -1;
    }
    else if (0 == n)
    {
        str[0] = '0';
        str[1] = '\0';
        return;
    }

    while (n)
    {
        *ptr++ = chars[n % radix];
        n /= radix;
    }

    if (negative)
    {
        *ptr++ = '-';
    }
    *ptr-- = 0;


    /* Reverse the string. */
    while (str < ptr)
    {
        tmp = *str;
        *str = *ptr;
        *ptr = tmp;
        str++;
        ptr--;
    }   
    return;
}

I'm a bit concerned because Spolsky claims in his articles that both of these functions can be written in about five lines, and both of these functions are longer than that. Maybe I'm missing something?