//3.编程实现:
//一组数据中只有一个数字出现了一次。其他所有数字都是成对出现的。
//请找出这个数字。(使用位运算)
#include<stdio.h>
#include<windows.h>
#include<math.h>
//方法一
int main()
{
int a[11] = {1,1,2,2,3,4,4,5,5};
int ret = 0;
int size;
//printf("Please input:\n");
//scanf_s("%d", &a);
size = sizeof(a) / sizeof(a[0]);
int i = 0;
for (; i < size; i+=2) //显然这样做的话,单独存在的数在前面代码没有问题,提前返回,但若是这个数在最后的话,便会越界
{
if ((a[i] ^ a[i + 1] )== 0)
{
;
}
else
{
break;
}
}
printf("%d\n", a[i]);
printf("%d\n", size);
//ret = shu(a[11],size);
system("pause");
return 0;
}
#include<stdio.h>
#include<windows.h>
#include<math.h>
//方法二
int main()
{
int a[11] = { 1, 1, 2, 2, 4, 4, 5, 5, 3 };
int ret = 0;
int size;
size = sizeof(a) / sizeof(a[0]);
int i = 0;
for (; i < size; i++)
{
ret^= a[i] ;//一个不同的数分别与成对出现的数按位异或,最终结果就是该单独出现的数,此法可解决方法一的越界问题
}
printf("%d\n", ret);
system("pause");
return 0;
}
一组数据中只有一个数字出现了一次,其他所有数字都是成对出现的,请使用位运算找出这个数字。
猜你喜欢
转载自blog.csdn.net/na_hanqiannan/article/details/80247298
今日推荐
周排行