25.03.2013 Views

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Solutions to Chapter 5 | Bit Manipulation<br />

5 1 You are given two 32-bit numbers, N and M, and two bit positions, i and j Write a<br />

method to set all bits between i and j in N equal to M (e g , M becomes a substring of<br />

N located at i and starting at j)<br />

1 3 3<br />

EXAMPLE:<br />

SOLUTION<br />

Input: N = 10000000000, M = 10101, i = 2, j = 6<br />

Output: N = 10001010100<br />

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

pg 58<br />

This code operates by clearing all bits in N between position i and j, and <strong>the</strong>n ORing to put<br />

M in <strong>the</strong>re<br />

1 public static int updateBits(int n, int m, int i, int j) {<br />

2 int max = ~0; /* All 1’s */<br />

3<br />

4 // 1’s through position j, <strong>the</strong>n 0’s<br />

5 int left = max - ((1

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

Saved successfully!

Ooh no, something went wrong!