Frage im Vorstellungsgespräch bei Zynga

Convert a string to an integer

Antworten zu Vorstellungsgespräch

Anonym

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

Anonym

6. Aug. 2012

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

Anonym

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.

Anonym

3. Juli 2015

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

Anonym

7. Juli 2010

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

Anonym

7. Juli 2010

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