Created
July 29, 2014 04:01
-
-
Save ivycheung1208/1c8a3e1d1f8d99da01ec to your computer and use it in GitHub Desktop.
CC150 5.1
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
/* CC150 5.1 | |
* You are given two 32-bit numbers, N and M, and two bit positions, i and j. | |
* Write a method to insert M into N such 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 of M. | |
* That is, if M= 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 = 100|0000|0000, M = 10011, i = 2, j = 6 | |
* Output: N = 100|0100|1100 | |
*/ | |
#include <iostream> | |
using namespace std; | |
int insert(int M, int N, int i, int j) | |
{ | |
for (int k = 0; i <= j; ++k, ++i) { | |
N &= (~(1 << i)); | |
N |= ((M & (1 << k)) << (i - k)); | |
} | |
return N; | |
} | |
int insert2(int M, int N, int i, int j) | |
{ | |
int left = ~0 << (j + 1); | |
int right = (1 << i) - 1; | |
return N & (left | right) | (M << i); | |
} | |
int main() | |
{ | |
int M, N; | |
cin >> M >> N; | |
int i, j; | |
cin >> i >> j; | |
cout << insert(M, N, i, j) << endl; | |
cout << insert2(M, N, i, j) << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment