1. A & B,得到的结果C中的1的位表明了A和B中相同的位都是1的位;
2. A | B, 得到的结果D中的1的位表明了A和B在该位至少有一个为1的位,包含了A 与 B 都是1的位数,
经过前两步的位运算,,C 中1的位表明了A 和 B在该位都是1,D中为0的位表明了A 和 B 在该位都是0 ,所以进行第三步。
3. C ^ D,E 中为1的位表明了A 和 B不同的位。
#include<iostream> using namespace std; int getNum(int n) { if(n==0) return 0; int count=0; while(n) { n&=(n-1); count++; } return count; } int main() { int A=43,B=101; int C=A&B; int D=A|B; int E=C^D; cout<<getNum(E)<<endl; system("pause"); return 0; }