問題描述:
程式設計實作:
一組資料中隻有一個數字出現了一次。其他所有數字都是成對出現的。
請找出這個數字。(使用位運算)
問題分析:
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;
}