qusition:Given a non-empty array of integers,every element appears twice for one .find that single one
1.普通写法
#include<stdio.h>
#include<stdlib.h>
int singlenumber(int *num,int numsize) {
int i, j, count;
// 遍历数组并打印所有元素
for(i = 0; i < numsize; i++) {
printf("%d ",num[i]);
}
printf("\n");
// 再次遍历数组,计算每个元素的出现次数
for(i = 0; i < numsize; i++) {
count = 0;
for(j = 0; j < numsize; j++) {
if(num[i] == num[j]) {
count++;
}
}
// 如果某个元素只出现一次,返回该元素
if(count == 1) {
return num[i];
}
}
// 如果数组中没有只出现一次的元素,返回0
return 0;
}
/*
num[0] = *(num+0)
num[1] = *(num+1)
num[2] = *(num+2)
*/
int main()
{
int arr[] = {1,1,4};
printf("The single number in the array is %d\n", singlenumber(arr,(sizeof(arr)/sizeof(*arr))));
return 0;
}
执行结果 :
2 2 4
The single number in the array is 4
2.快速运算(bitewise XOR)
bitewise XOR规则: A^A = 0 ;A^0 = A
#include<stdio.h>
int singlenumber(int *num,int numsize)
{
for(int i=0;i < numsize;i++)//用来遍历
{
printf("%d ",num[i]);
}
printf("\n");
int n = num[0];
for(int j = 1;j <numsize;j++)
{
n ^= num[j];
}
return n;
}
int main()
{
int arr[] = {2,2,4};
printf("The single number in the array is %d\n", singlenumber(arr,(sizeof(arr)/sizeof(*arr))));
return 0;
}
运行结果
2 2 4
The single number in the array is 2