C语言编程 找出数列中只出现了一次的数字(其他所有数字都是成对出现)

仅限于此题,最好的解决方案是使用按位异或的计算方法来计算

使用的是按位异或计算时“相同的数字计算会得到0,0和任何数字按位异或计算得到的是任何数字”的特性。

源代码:

#include<stdio.h>
#include<stdlib.h>
int rearch(int array[],int length)
{
    int i,result=0;
    for (i = 0; i < length; i++)
    {
        result ^= array[i];//将所有数列中的数字按位异或
    }
    return result;
}
int main()
{
    int result;
    int array[13] = { 1,9,8,1,8,9,2,4,5,3,4,5,2 };
    result = rearch(array,13);
    printf("只出现了一次的元素是%d\n", result);
    system("pause");
    return 0;
}
posted @ 2019-04-21 11:46  Kaniso_Vok  阅读(169)  评论(0编辑  收藏  举报