Pergunta de entrevista da empresa Amazon

Write a function that allows to convert a string to the corresponding number (i.e. implement the atoi() C function)

Respostas da entrevista

Sigiloso

23 de mar. de 2011

int my_atoi(char* pStr) { if (pStr == NULL) { printf("ERROR: null string.\n"); return -1; } int num = 0; int pos; for (pos = 0; ; pos++) { char currChar = *(pStr+pos); // Check whether the current char is not a digit if ( currChar '9' ) return num; // Read the number and add it to the 'num' variable num = (num*10) + (int) currChar - (int)'0'; } return num; }

4

Sigiloso

25 de mar. de 2011

int atoi(char *s) { int i = 0; while(*s) { i = (i<<3) + (i<<1) + (*s - '0'); s++; } return i; }

Sigiloso

25 de mar. de 2011

int atoi(char *s) { int i=0; while(*s) { i = i*10 + (*s- '0'); s++; } return i; }

Sigiloso

25 de mar. de 2011

Try testing for the above to sample codes, I have not really tested it on any compilers.