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

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

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

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

EXAMPLE:<br />

SOLUTION<br />

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

Output: N = 10001010100<br />

pg 58<br />

This code operates by clearing all bits in N between position i <strong>and</strong> j, <strong>and</strong> <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!