剑指Offer----扩展:二进制(小米)

问题描述:


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


输入例子:1999 2299
输出例子:7


分析:将两个整数逐位进行比较,累加不同位的个数,直至两个数都为0.


方法一:


比较两个数的最后一位,然后分别右移一位,直至两个数都为0.


源代码:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>

int countBitDiff(int m, int n)
{
	int count = 0;
	while (m != 0 || n != 0)
	{
		if ((m & 0x1) != (n & 0x1))
			++count;
		m >>= 1;
		n >>= 1;
	}
	return count;
}

int main()
{
	int m, n;
	while (scanf("%d %d", &m, &n) == 2)
	{
		printf("%d\n", countBitDiff(m, n));
	}
	
	printf("%s  %s\n", __DATE__, __TIME__);
	system("pause");
	return 0;
}


运行结果:

1999 2299
7
123456 654321
8
^Z
Aug 28 2016  20:02:54
请按任意键继续. . .


方法二


此方法要多感谢下边第一位评论网友的点拨,先将两个数进行异或,然后统计异或得到的结果中1的位数。

源代码:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>

int countBitDiff(int m, int n)
{
	int temp = m^n;
	int count = 0;
	while (temp)
	{
		++count;
		temp = temp&(temp - 1);
	}
	return count;
}

int main()
{
	int m, n;
	while (scanf("%d %d", &m, &n) == 2)
	{
		printf("%d\n", countBitDiff(m, n));
	}

	printf("%s  %s\n", __DATE__, __TIME__);
	system("pause");
	return 0;
}

运行结果:
1999 2299
7
^Z
Aug 29 2016  16:07:15
请按任意键继续. . .








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值