Pregunta de entrevista de Zynga

Convert a string to an integer

Respuestas de entrevistas

Anónimo

10 sep 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

Anónimo

6 ago 2012

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

Anónimo

10 nov 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.

Anónimo

3 jul 2015

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

Anónimo

7 jul 2010

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

Anónimo

7 jul 2010

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