C语言:一组数据中只有一个数字出现了一次。其他所有数字都是成对出现的。 请找出这个数字。

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

分析:对于一组数中只有一个数只出现一次,其他所有数都是成对出现的,我们采用对全部数组元素进行异或,便可得到结果

#include<stdio.h>
#include<stdlib.h>

int main()
{
    int arr[7] = { 1, 2, 3, 1, 2,3,4 };
    int i = 0;
    int sz = sizeof(arr)/ sizeof(arr[0]);
    int ret = 0;
    for (i = 0; i < sz; i++)
    {
        ret = ret^arr[i];
    }
    printf("出现一次的数是:%d\n", ret);
    system("pause");
    return 0;
}


 

猜你喜欢

转载自blog.csdn.net/qq_42270373/article/details/81172544
今日推荐