世界上有10种人,一种懂二进制,一种不懂。那么你知道两个int32整数m和n的二进制表达,有多少个位(bit)不同么?

// ConsoleApplication10.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
using namespace std;

class Solution {
public:
	/**
	* 获得两个整形二进制表达位数不同的数量
	*
	* @param m 整数m
	* @param n 整数n
	* @return 整型
	*/
	//首先两个数异或,不同为1
	//然后移位
	int countBitDiff(int m, int n) {
		int re = m^n;
		int num = 0;
		
		while (re!=0)
		{
			if ((re & 1) == 1)
			{
				++num;
			}
			re=re >> 1;
		}
		return num;
	}
};

int main()
{
	Solution so;
	cout<<"num:"<<so.countBitDiff(1999, 2299);
	cout << endl;
	return 0;
}
posted @ 2017-02-18 15:55  wdan2016  阅读(1020)  评论(0编辑  收藏  举报