代码题--C++--懂二进制两个int32整数的二进制不同的个数
题目描述
世界上有10种人,一种懂二进制,一种不懂。那么你知道两个int32整数m和n的二进制表达,有多少个位(bit)不同么?
示例1
输入
1999 2299
返回值
7
解题思路1:因为32位,所以循环次数是32,然后二进制位的末尾呢个数字其实就是取余2之后的值,然后一个一个判断之后的,每次将值右移1(m>>1;n>>1;),也相当于除以2(m/=2;n/=2;)。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
/**
* 获得两个整形二进制表达位数不同的数量
*
* @param m 整数m
* @param n 整数n
* @return 整型
*/
int countBitDiff(int m, int n) {
int res = 0;
for (int i = 0; i < 32; i++)
{
if (m % 2 != n % 2)
{
res++;
}
m /= 2;
n /= 2;
}
return res;
}
};
int main()
{
Solution sa;
int m, n;
cin >> m >> n;
cout << sa.countBitDiff(m,n);
return 0;
}
解题思路2:异或的意思就是两个二进制数的当前位是否相等,如果不同,当前位答案就是1,所以用temp记录之后,遍历这个32位的二进制的数字有多少个1((temp >> i) & 0x01),其中i从0到32,意义就是将数字temp的二进制左移i位,然后&0x01(与1)目的是统计末尾数字有1的个数,这样就可以得出答案了。
代码如下:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
/**
* 获得两个整形二进制表达位数不同的数量
*
* @param m 整数m
* @param n 整数n
* @return 整型
*/
int countBitDiff(int m, int n) {
int temp = m ^ n;//m和n 异或
int i = 0, num = 0;
while (i < 32)
{
if ((temp >> i) & 0x01)
num++;
i++;
}
return num;
}
};
int main()
{
Solution sa;
int m, n;
cin >> m >> n;
cout << sa.countBitDiff(m,n);
return 0;
}