Zynga Interview Question

Convert a string to an integer

Interview Answers

Anonymous

Sep 10, 2009

Not exactly super, but should do for a whiteboard: int myatoi (char *str) { int retval; int sign; sign = 1; if (*str == '-') { sign = -1; str++; } retval = 0; while (*str) { retval *= 10; retval += *str - '0'; str++; } return (retval * sign); }

2

Anonymous

Aug 6, 2012

The pointer is a char pointer, so the loop (and the sign check) are on a character by character basis.

Anonymous

Nov 10, 2013

Brian is right, he is using C char pointers, and can compare a character at a time. This is not Java, this does work.

Anonymous

Jul 3, 2015

int.Parse(str) hah. But in all seriousness, the aforementioned solution is good.

Anonymous

Jul 7, 2010

Bug, The check is just for the first character of the string - your version will not even compile...

Anonymous

Jul 7, 2010

I think, there is bug at statement if (*str == '-1') ........ what if str = "-1234"