Question d’entretien chez Amazon

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

Réponses aux questions d'entretien

Utilisateur anonyme

23 mars 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

Utilisateur anonyme

25 mars 2011

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

Utilisateur anonyme

25 mars 2011

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

Utilisateur anonyme

25 mars 2011

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