Skip to content

Instantly share code, notes, and snippets.

@WOLOHAHA
Created July 23, 2014 15:34
Show Gist options
  • Save WOLOHAHA/2b30d73ab3c00c65b1ab to your computer and use it in GitHub Desktop.
Save WOLOHAHA/2b30d73ab3c00c65b1ab to your computer and use it in GitHub Desktop.
You are given two 32-bit numbers, N and M, and two bit positions, i and j Write a method to set all bits between i and j in N equal to M (e g , M becomes a substring of N located at i and starting at j)
package POJ;
public class Main{
/**
*
* 5.1 You are given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to set all bits
* between i and j in N equal to M (e g , M becomes a substring of N located at i and starting at j)
*
* EXAMPLE:
* Input: N = 10000000000, M = 10101, i = 2, j = 6
* Output: N = 10001010100
*
* Solution:
* 1. clear the bits j through i in N
* 2. shift M so that it lines up with bits j through i
* 3. merge M and N
*
*/
public int updateBits(int n, int m, int i, int j) {
// create a mask to clear bits i through j in n
// Example: i=2, j=4, result should be 11100011
// for simplicity, we'll use just 8 bits for the example
int allOnes = ~0; // will equal sequence of all 1s
int left = allOnes << (j + 1); // left: 11100000
int right = ((1 << i) - 1); // right:00000011
int mask = left | right; // mask: 11100011
// clear bits j through i then put m in there
int n_cleared = n & mask; // clear bits j through i
int m_shifted = m << i; // move m into correct position
return (n_cleared | m_shifted);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment