Here are some more simple programming exercises:
atoi()
itoa()
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?
I'm Stephen Van Dahm, a software developer from Minneapolis, Minnesota.
Graphic design is hard! Let's go shopping!
After reading James Bennett's latest post, I immediately tried the following Unix command....
I don't know what the folks at Apple were smoking when they decided to build that ugly, glassy fake 3D Dock into Leopard. There is no way in hell that I'm going to look at that every day for the next two years. Fortunately, there appears to be a solution.
Read every post I've ever written, because I'm such an interesting guy.