25.03.2013 Views

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Solutions to Chapter 1 | Arrays and Strings<br />

1 2 Write code to reverse a C-Style String (C-String means that “abcd” is represented as<br />

five characters, including <strong>the</strong> null character )<br />

SOLUTION<br />

CareerCup com<br />

pg 48<br />

This is a classic interview question The only “gotcha” is to try to do it in place, and to be careful<br />

for <strong>the</strong> null character<br />

1 void reverse(char *str) {<br />

2 char * end = str;<br />

3 char tmp;<br />

4 if (str) {<br />

5 while (*end) {<br />

6 ++end;<br />

7 }<br />

8 --end;<br />

9 while (str < end) {<br />

10 tmp = *str;<br />

11 *str++ = *end;<br />

12 *end-- = tmp;<br />

13 }<br />

14 }<br />

15 }<br />

9 6

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!