Amazon interview question

Implement atoi

Interview Answers

Anonymous

Oct 8, 2011

int myatoi(char *string) { int val = 0; if (string) { // Error checking to eliminate NULL string while (*string && *string = '0') { val = (val * 10) + (*string - '0'); string++; if (*string != '\0' && !(*string = '0')) return 0; // Error checking to eliminate cases like '12ABC34' } } return val; }

Anonymous

Oct 16, 2011

atoi also handles the case when there is a leading plus or minus in the string. Also it doesnt go to the end of the string. Just till the first white space character in the string

Anonymous

Nov 2, 2011

int my_atoi(char *str) { int ret = 0,sign=1; if(*str == '-') { sign = -1; str++; } while(*str) { ret = (ret * 10) + (*str - '0'); str++; } return ret*sign; }