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 20 | Hard<br />

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

SOLUTION<br />

pg 91<br />

To investigate this problem, let’s start off by gaining a deeper underst<strong>and</strong>ing 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, <strong>and</strong> 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” <strong>and</strong><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 <strong>and</strong> 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 <strong>and</strong><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 <strong>and</strong> 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!