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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Solutions</strong> to Chapter 6 | Brain Teasers<br />

6.1 Add arithmetic operators (plus, minus, times, divide) to make <strong>the</strong> following expression<br />

true: 3 1 3 6 = 8. You can use any paren<strong>the</strong>ses you’d like.<br />

SOLUTION<br />

pg 60<br />

An interviewer is asking this problem to see how you think <strong>and</strong> approach problems—so<br />

don’t just guess r<strong>and</strong>omly.<br />

Try approaching this <strong>the</strong> following way: What sorts of operations would get us to 8? I can<br />

think of a few:<br />

4 * 2 = 8<br />

16 / 2 = 8<br />

4 + 4 = 8<br />

Let’s start with <strong>the</strong> first one. Is <strong>the</strong>re any way to make 3 1 3 6 produce 4 * 2? We can easily<br />

notice that 3 + 1 = 4 (<strong>the</strong> first two numbers). We can also notice that 6 / 3 = 2. If we had “3 1<br />

6 3”, we’d be done, since (3 + 1)*(6 / 3) = 8. Although it seems a little unconventional to do<br />

this, we can, in fact, just flip <strong>the</strong> 6 <strong>and</strong> <strong>the</strong> 3 to get <strong>the</strong> solution:<br />

(( 3 + 1 ) / 3) * 6 = 8<br />

1 4 3<br />

<strong>Cracking</strong> <strong>the</strong> <strong>Coding</strong> <strong>Interview</strong> | Concepts <strong>and</strong> Algorithms

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

Saved successfully!

Ooh no, something went wrong!