写一个程序交换一个整数二进制形式中的奇数位和偶数位。(用尽可能少的操作)
思路:设整数位n,将n和0x55555555进行与运算并左移一位记录偶数位;将n右移一位再和0x55555555进行与运算记录奇数位,然后进行或运算即可。
#include <iostream> #include <stack> using namespace std; int SwapBits(int n) { return ((n & 0x55555555) << 1) | ((n >> 1) & 0x55555555); } void PrintBinary(int n) { stack<int> stk; for (int i = 0; i < 32; ++i) { if (n & 1 == 1) stk.push(1); else stk.push(0); n >>= 1; } while (!stk.empty()) { cout << stk.top(); stk.pop(); } cout << endl; } int main() { int a; while (cin >> a) { cout << SwapBits(a) << endl; PrintBinary(a); PrintBinary(SwapBits(a)); } return 0; }