25.03.2013 Views

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

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.

Solutions to Chapter 20 | Hard<br />

20 1 Write a function that adds two numbers You should not use + or any arithmetic operators<br />

SOLUTION<br />

2 7 9<br />

<strong>Cracking</strong> <strong>the</strong> <strong>Coding</strong> <strong>Interview</strong> | Additional Review Problems<br />

pg 91<br />

To investigate this problem, let’s start off by gaining a deeper understanding of how we add<br />

numbers We’ll work in Base 10 so that it’s easier to see To add 759 + 674, I would usually add<br />

digit[0] from each number, carry <strong>the</strong> one, add digit[1] from each number, carry <strong>the</strong> one, etc<br />

You could take <strong>the</strong> same approach in binary: add each digit, and carry <strong>the</strong> one as necessary<br />

Can we make this a little easier? Yes! Imagine I decided to split apart <strong>the</strong> “addition” and<br />

“carry” steps That is, I do <strong>the</strong> following:<br />

1 Add 759 + 674, but “forget” to carry I <strong>the</strong>n get 323<br />

2 Add 759 + 674 but only do <strong>the</strong> carrying, ra<strong>the</strong>r than <strong>the</strong> addition of each digit I <strong>the</strong>n<br />

get 1110<br />

3 Add <strong>the</strong> result of <strong>the</strong> first two operations (recursively, using <strong>the</strong> same process described<br />

in step 1 and 2): 1110 + 323 = 1433<br />

Now, how would we do this in binary?<br />

1 If I add two binary numbers toge<strong>the</strong>r but forget to carry, bit[i] will be 0 if bit[i] in a and<br />

b are both 0 or both 1 This is an XOR<br />

2 If I add two numbers toge<strong>the</strong>r but only carry, I will have a 1 in bit[i] if bit[i-1] in a and b<br />

are both 1’s This is an AND, shifted<br />

3 Now, recurse until <strong>the</strong>re’s nothing to carry<br />

1 int add_no_arithm(int a, int b) {<br />

2 if (b == 0) return a;<br />

3 int sum = a ^ b; // add without carrying<br />

4 int carry = (a & b)

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

Saved successfully!

Ooh no, something went wrong!