1.題目
一組數據中只有一個數字出現了一次。其他所有數字都是成對出現的。
請找出這個數字。
2.程序代碼
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <Windows.h>
int find_num(int arr1[9])
{
int i = 0;
int j = 0;
int arr2[9] = {0};//定義一個數組,來與原數組比較
for (i = 0; i < 9; i++)
{
arr2[i] = arr1[i];//把原數組的值賦給新數組
for (j = 0; j < 9; j++)
{
if ((arr1[i] == arr1[j])&&(i != j))//對比當前數組的某個元素與其他元素
{
arr2[i]++;//如果有相同的,就給新數組加一
}
}
}
for (i = 0; i < 9; i++)
{
if (arr1[i] == arr2[i])//只有原數組中沒有對應相同的數字,新數組中的該元素才與原數組相同
{
return arr1[i];
}
}
}
int main()
{
int arr[9] = { 1, 2, 3, 4, 5, 4, 3, 2, 1 };
int ret = 0;
ret = find_num(arr);
printf("只出現一次的數字爲:%d\n", ret);
system("pause");
return 0;
}
//簡便寫法,使用位運算
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <Windows.h>
int find_num(int arr[9])
{
int i = 0;
int count = arr[0];
for (i = 1; i < 9; i++)
{
count = count ^ arr[i];//把數組中所有元素都按位與,相等的兩個數按位與爲0,
//所以最後只剩下沒有成對的數字
}
return count;
}
int main()
{
int arr[9] = { 1, 2, 3, 4, 5, 4, 3, 2, 1 };
printf("只出現一次的數字爲:%d\n", find_num(arr));
system("pause");
return 0;
}