《Cracking the Coding Interview》——第5章:位操作——题目6

2014-03-19 06:24

题目:将一个整数的奇偶二进制位交换,(0, 1) (2, 3) ...

解法:使用掩码来进行快速交换,定义掩码为'0101...'和‘1010...’。

代码:

 1 // 5.6 Swap odd and even bits in an integer.

 2 #include <cstdio>

 3 using namespace std;

 4 

 5 unsigned int swapBits(unsigned int n)

 6 {

 7     static const unsigned int mask[2] = {0x55555555, 0xaaaaaaaa};

 8     

 9     return ((n & mask[0]) << 1) + ((n & mask[1]) >> 1);

10 }

11 

12 int main()

13 {

14     unsigned int n;

15     

16     while (scanf("%u", &n) == 1) {

17         printf("%u\n", swapBits(n));

18     }

19     

20     return 0;

21 }

 

你可能感兴趣的:(interview)