2014-03-19 05:45

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

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

代码:

 1 // 5.1 Insert one number into the certain bit segment of another number.
 2 #include <cstdio>
 3 using namespace std;
 4 
 5 void printBinary(unsigned num)
 6 {
 7     unsigned bit = 1 << 31;
 8     
 9     do {
10         putchar('0' + !!(num & bit));
11         bit >>= 1;
12     } while (bit);
13 }
14 
15 unsigned insertBits(unsigned n, unsigned m, int ll, int rr)
16 {
17     return (n >> (rr + 1) << (rr + 1)) + (m << ll) + (n - (n >> ll << ll));
18 }
19 
20 int main()
21 {
22     unsigned n, m;
23     unsigned res;
24     int low, high;
25     
26     while (scanf("%u%u", &n, &m) == 2) {
27         scanf("%d%d", &low, &high);
28         res = insertBits(n, m, low, high);
29         printBinary(n);
30         putchar('\n');
31         printBinary(m);
32         putchar('\n');
33         printBinary(res);
34         putchar('\n');
35     }
36     
37     return 0;
38 }

 

 posted on 2014-03-19 05:48  zhuli19901106  阅读(225)  评论(0编辑  收藏  举报