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 5 | Bit Manipulation<br />

5.4 Explain what <strong>the</strong> following code does: ((n & (n-1)) == 0).<br />

SOLUTION<br />

pg 58<br />

We can work backwards to solve this question.<br />

What does it mean if A & B == 0?<br />

It means that A <strong>and</strong> B never have a 1 bit in <strong>the</strong> same place. So if n & (n-1) == 0, <strong>the</strong>n n <strong>and</strong><br />

n-1 never share a 1.<br />

What does n-1 look like (as compared with n)?<br />

Try doing subtraction by h<strong>and</strong> (in base 2 or 10). What happens?<br />

1101011000 [base 2]<br />

- 1<br />

= 1101010111 [base 2]<br />

593100 [base 10]<br />

- 1<br />

= 593099 [base 10]<br />

When you subtract 1 from a number, you look at <strong>the</strong> least significant bit. If it’s a 1 you change<br />

it to zero <strong>and</strong> you are done. If it’s a zero, you must “borrow” from a larger bit. So, you go to<br />

increasingly larger bits, changing each bit from a 0 to a 1, until you find a 1. You flip that one<br />

to a 0 <strong>and</strong> you are done.<br />

Thus, n-1 will look like n, except that n’s initial 0s will be 1’s in n-1, <strong>and</strong> n’s least significant 1<br />

will be a 0 in (n-1). That is:<br />

if n = abcde1000<br />

<strong>the</strong>n n-1 = abcde0111<br />

So what does n & (n-1) == 0 indicate?<br />

n <strong>and</strong> (n-1) must have no 1s in common. Given that <strong>the</strong>y look like this:<br />

if n = abcde1000<br />

<strong>the</strong>n n-1 = abcde0111<br />

abcde must be all 0s, which means that n must look like this: 00001000. n is <strong>the</strong>refore a<br />

power of two.<br />

So, we have our answer: ((n & (n-1)) == 0) checks if n is a power of 2 (or 0).<br />

CareerCup.com<br />

1 3 8

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

Saved successfully!

Ooh no, something went wrong!