天天看点

一组数据中只有一个数字出现了一次。其他所有数字都是成对出现的。  请找出这个数字。(使用位运算)

问题描述:

编程实现: 

一组数据中只有一个数字出现了一次。其他所有数字都是成对出现的。 

请找出这个数字。(使用位运算) 

问题分析:

1、输入一串数字保存在数组里;

2 、int len = sizeof(数组名) / sizeof(数组名[0]),求出数组长度,固定公式;

3、以数组长度为循环次数,开始循环;

4、int result = 0;  result ^= a[i];   相同异或为零,相宜异或为一,任何数和零异或都为它本身;(核心思想)

5、打印输出结果。

源代码:

#include <stdio.h>
#include <windows.h>
#pragma warning (disable:4996)


void main()
{
	int a[] = { 1, 2, 3, 4, 2, 4, 2, 3, 2, 5, 1 };
	int len = sizeof(a) / sizeof(a[0]);
	int i = 0;
	int result = 0;
	for (i = 0; i < len; i++)
	{
		printf("%2d", a[i]);
	}
	printf("\n");
		for (i = 0; i < len; i++)
		{
			result ^= a[i];
		}
		printf("The result = %d\n", result);
		system("pause");
		return 0;
	}
           

继续阅读