27.10.2014 Views

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

<strong>Solutions</strong> to Chapter 1 | Arrays <strong>and</strong> 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 />

pg 48<br />

This is a classic interview question. The only “gotcha” is to try to do it in place, <strong>and</strong> 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 />

CareerCup.com<br />

9 6

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

Saved successfully!

Ooh no, something went wrong!