C语言求两个数中不同的位的个数

Posted lytwajue

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C语言求两个数中不同的位的个数相关的知识,希望对你有一定的参考价值。

//求两个数中不同的位的个数
#include <stdio.h>
int count_different(int a, int b)
{
	int count = 0;
	int c = a^b;        //a,b中不同的位即为1
	while (c)
	{
		count++;
		c = c&(c - 1);  //把c中最后一个1去掉
	}
	return count;
}
int main()
{
	printf("%d\n", count_different(3,8));   //3
	printf("%d\n", count_different(0, 6));  //2
	printf("%d\n", count_different(-1,1));  //31
	return 0;
}

以上是关于C语言求两个数中不同的位的个数的主要内容,如果未能解决你的问题,请参考以下文章