PTA: Single Number (15 minutes) (C language)

Given a non-empty array of integers, every element appears twice except for one. Find that single one.

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Tip:

You can use bitwise to solve this problem.

Interface definition function:
Long Long singleNumber (Long Long the nums *, int numsSize);

Referee test sample program:
#include <stdio.h>
#define MAXN 1000005

long long nums[MAXN];

long long singleNumber(long long* nums, int numsSize);

int main ()
{

int N;

scanf("%d", &N);
for(int i = 0; i < N; i++)
scanf("%lld", &nums[i]);

printf("%lld", singleNumber(nums, N));

return 0;

}

/ * Please fill in the answer here * /

Input Sample 1:
. 3
2 2 1

Output Sample 1:
1

Input Sample 2:
. 5
. 4. 1. 1 2 2

Output Sample 2:
4

long long singleNumber(long long* nums, int numsSize)
{
    int i;
    long long ans = nums[0];
    for (i = 1; i < numsSize; i++)
        ans = ans ^ nums[i];
    return ans;

}
Published 58 original articles · won praise 21 · views 605

Guess you like

Origin blog.csdn.net/qq_45624989/article/details/105399578