Created
July 28, 2014 00:04
-
-
Save UncleGarden/808982dd62823f43127f to your computer and use it in GitHub Desktop.
CareerCup 150
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 5.1 You are given two 32-bit numbers, N andM, and two bit positions, i and j. | |
* Write a method to insert M into Nsuch that M starts at bit j and ends at bit | |
* i. You can assume that the bits j through i have enough space to fit all ofM. | |
* That is, ifM= 10011, you can assume that there are at least 5 bits between j | |
* and i. You would not, for example, have j-3 and i=2, because M could not | |
* fully fit between bit 3 and bit 2. EXAMPLE: Input: N = 10000000000, M = | |
* 10011, i = 2, j = 6 Output: N = 10001001100 | |
* | |
* | |
* @author Garden | |
*/ | |
public class CC5_1 { | |
public static int insert(int N, int M, int i, int j) { | |
//to all ones: 11111111111111111111111111111111 | |
int allOne = ~0; | |
//all ones before j, then 0s | |
int left = allOne << (j + 1); | |
//all 0s before i, then 1s | |
int right = ((1 << i) - 1); | |
//all ones, but range i - j are 0s | |
int mask = left | right; | |
//clear bits through j to i | |
int clear = N & mask; | |
//move M to the right place | |
int shift = M << i; | |
//clear | shift | |
return clear | shift; | |
} | |
public static void main(String[] args) { | |
int N = 0b10000000000; | |
int M = 0b10011; | |
int i = 2; | |
int j = 6; | |
System.out.println(Integer.toBinaryString(insert(N, M, i, j))); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment