位运算与函数指针
#include <stdio.h> #include <string> #include <algorithm> using namespace std; #define exchange(a,b) { a^=b; b^=a; a^=b; } #define comp(a,b) ( (1ull<<((sizeof(a-b) * 8) - 1)) & (long long) floor((a-b)) ? b : a ) //不用任何大于小于符合比较两数大小 //函数指针 typedef int (*cmpFcn) (int); //cmpFcn是一种指向函数指针类型的名字,该指针类型指向一个返回int类型,并带有一个int形参的函数 bool (*qt) (const string &, const string &); int get(int a) { a = a ^ ( a >> 1 ); a = a ^ ( a >> 2 ); a = a ^ ( a >> 4 ); a = a ^ ( a >> 8 ); a = a ^ ( a >> 16 ); return a; } int getnum(int x) { x = (x & 0x55555555) + ( (x>>1)&(0x55555555) ); x = (x & 0x33333333) + ( (x>>2)&(0x33333333) ); x = (x & 0x0F0F0F0F) + ( (x>>4)&(0x0F0F0F0F) ); x = (x & 0x00FF00FF) + ( (x>>8)&(0x00FF00FF) ); x = (x & 0x0000FFFF) + ( (x>>16)&(0x0000FFFF) ); return x; } int main( ) { int a,b; while( scanf("%d%d",&a,&b) != EOF ) { exchange(a,b); printf("交换后:"); printf("%d %d\n",a,b); printf("求a中有偶数个1还是奇数个1:\n"); cmpFcn pf; pf = get; printf("16进制 a = %x\n",a); pf(a); if( !(a&1) ) puts("a中有偶数个1"); else puts("a中有奇数个1"); puts("求b中有多少个1"); printf("16进制 b = %x\n",b); pf = getnum; printf("%d\n",pf(b)); } return 0; }