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.

Chapter 5 | Bit Manipulation<br />

How to Approach:<br />

Bit manipulation can be a scary thing to many c<strong>and</strong>idates, but it doesn’t need to be! If you’re<br />

shaky on bit manipulation, we recommend doing a couple of arithmetic-like problems to<br />

boost your skills. Compute <strong>the</strong> following by h<strong>and</strong>:<br />

1010 - 0001 1010 + 0110 1100^1010<br />

1010 > 1 0xFF - 1 0xAB + 0x11<br />

If you’re still uncomfortable, examine very carefully what happens when you do subtraction,<br />

addition, etc in base 10. Can you repeat that work in base 2?<br />

NOTE: The Windows Calculator knows how to do lots of operations in binary,<br />

including ADD, SUBTRACT, AND <strong>and</strong> OR. Go to View > Programmer to get into<br />

binary mode while you practice.<br />

Things to Watch Out For:<br />

»»<br />

It’s really easy to make mistakes on <strong>the</strong>se problems, so be careful! When you’re writing<br />

code, stop <strong>and</strong> think about what you’re writing every couple of lines - or, better yet, test<br />

your code mid-way through! When you’re done, check through your entire code.<br />

»»<br />

If you’re bit shifting, what happens when <strong>the</strong> digits get shifted off <strong>the</strong> end? Make sure<br />

to think about this case to ensure that you’re h<strong>and</strong>ling it correctly.<br />

And (&): 0 & 0 = 0 1 & 0 = 0 0 & 1 = 0 1 & 1 = 1<br />

Or (|): 0 | 0 = 0 1 | 0 = 1 0 | 1 = 1 1 | 1 = 1<br />

Xor (^): 0 ^ 0 = 0 1 ^ 0 = 1 0 ^ 1 = 1 1 ^ 1 = 0<br />

Left Shift:<br />

x > 2 = 00000110<br />

00011001 >> 4 = 00000001<br />

5 7<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!