NVIDIA Interview Question
Software Engineer / DevelopersNot bad as long as you don't pass in a sign, or null, or characters other than digits. :) Granted an interviewer is probably just looking for what you did.
int isDigit16(char* p)
{
return isDigit10(p) || ((*p) >= 'a' && (*p) <= 'f') || ((*p) >= 'A' && (*p) <= 'F');
}
int atoi(char* p)
{
int cur;
int sign = 1;
int base = 10;
int total = 0;
if (!p || !p[0]) return 0;
while (p[cur] == ' ' || p[cur] == '\t') cur++;
if (!p[cur]) return 0;
if (p[cur] == '-')
{
sign = -1;
cur++;
}
if (p[cur] == '0')
{
if (p[cur+1] == 'x' || p[cur+1] == 'X')
{
base = 16;
cur += 2;
}
else
{
base = 8;
cur++;
}
}
while (p[cur])
{
switch(base)
{
case 8:
if (isDigit8(&p[cur])
{
total = total * 8 + p[cur] - '0';
break;
}
else return sign*total;
case 10:
if (isDigit(&p[cur])
{
total = total * 10 + p[cur] - '0';
break;
}
else return sign*total;
case 16:
if (isDigit16(&p[cur])
{
int d = (p[Cur]<='9')?(p[cur]-'0'):(((p[cur]<='F')?p[cur]-'A':p[cur]-'a')+10);
total = total * 16 + d;
break;
}
else return sign*total;
}
cur++;
}
return sign*total;
}
forget to copy some of the prerequisites
int isDigit10(char* p)
{
return (*p) >= '0' && (*p) <= '9';
}
int isDigit8(char* p)
{
return (*p) >= '0' && (*p) <= '7';
}
check the official atoi spec, out of range result in undefined behavior. So the above implementation should be fine.
Language: C++
Method:
- Get the length of the cstring
- Based on the length, we can figure out the base to start with.
For example '123', gives a size of 3, therefore the starting base will be pow(10,3);
- In the for-loop, we decrease base as we go down the char array
- Multiply each (ascii code - ascii code ('0')) with the base;
- Add the result to the variable temp (that keeps incrementing as we add values);
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <cmath>
#define SYMBOL 48
int atoi (char * numbers);
int main (int argc, char ** argv) {
//initialize the string
char numbers[] = "0123456";
//atoi(numbers);
printf ("%d \n",atoi(numbers));
}
int atoi (char * numbers) {
printf ("size of string:%lu\n", strlen(numbers));
int temp = 0;
int base = pow(10,strlen(numbers)-1);
//printable characters from 0 to 9 have an ascii code from 48 to 57
//just substracting 48 from the ascii code should give the correct value
//to keep things simple, we check if the ascii value is within the range we are handling
for (int i=0; i < strlen(numbers);i++) {
if (numbers[i] < 48 || numbers[i] >57) {
printf ("the string contains illegal symbols, limit characters to range 0 to 9\n");
return 0;
}
temp += ((int)(numbers[i])-SYMBOL)*base;
printf ("temp: %u\n", temp);
base = base/10;
}
return temp;
}
int atoi(char *p)
- D October 16, 2008{
int total = 0;
int i=0;
while(p[i] != '\0')
{
total *= 10;
total += p[i] - '0';
i++;
}
return total;
}