2014-03-19 05:45

题目:给定两个数M和N,将N按照二进制位,覆盖到M的特定段位中去。

解法:位操作,请看代码。

代码:

 // 5.1 Insert one number into the certain bit segment of another number.
#include <cstdio>
using namespace std; void printBinary(unsigned num)
{
unsigned bit = << ; do {
putchar('' + !!(num & bit));
bit >>= ;
} while (bit);
} unsigned insertBits(unsigned n, unsigned m, int ll, int rr)
{
return (n >> (rr + ) << (rr + )) + (m << ll) + (n - (n >> ll << ll));
} int main()
{
unsigned n, m;
unsigned res;
int low, high; while (scanf("%u%u", &n, &m) == ) {
scanf("%d%d", &low, &high);
res = insertBits(n, m, low, high);
printBinary(n);
putchar('\n');
printBinary(m);
putchar('\n');
printBinary(res);
putchar('\n');
} return ;
}
05-28 18:09