Pergunta de entrevista da empresa Zynga

Convert a string to an integer

Respostas da entrevista

Sigiloso

10 de set. de 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

Sigiloso

6 de ago. de 2012

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

Sigiloso

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

Sigiloso

3 de jul. de 2015

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

Sigiloso

7 de jul. de 2010

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

Sigiloso

7 de jul. de 2010

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