采用位运算。将num1和num2按位异或得到num,再统计num中二进制1的个数,即是不同的位数。代码比较简单,如下:

#include <iostream>
using namespace std;

int countDiffBin(int num1, int num2) {
    int num = num1^num2;
    int cnt = 0;
    while(num) {
        ++cnt;
        num = num&(num-1);
    }

    return cnt;
}

int main()
{
    int n1, n2;
    while(cin >> n1 >> n2) {
        cout << countDiffBin(n1, n2) << endl;
    }

    return 0;
}