5.6 Write a program to swap odd and even bits in an integer with as few instructions as possible (e.g., bit 0 and bit 1 are swapped, bit 2 and bit 3 are swapped, and soon).
這道題讓我們交換奇偶位,那麼我們首先還是要考慮用位操作Bit Manipulation來做,我們知道由於奇偶位是相鄰的,奇數位平移一位就是偶數位,反過來偶數位平移一位就是奇數位,那麼這題我們可以分別將原來的奇數位和偶數位分別提取出來,各自平移一位,再將其混合成結果即可。提取的方法我們用mask來,對於一個32位的整型數,其奇數位的二進位制的mask為10101010101010101010101010101010,換成十六進位制數為0xaaaaaaaa,同理偶數位的二進位制的mask為01010101010101010101010101010101,換成十六進位制數為0x55555555,平移完將其或起來即可,參見程式碼如下:
class Solution { public: int swapOddEvenBits(int x) { return (((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1)); } };