Find the odd number of occurrences in the array where the other numbers are all even

Find the odd number of occurrences in the array where the other numbers are all even

Title description

Give an array arr, in which only one number appears odd times, and the other numbers appear even times, print this number.

Enter a description:

The input contains two lines, the first line contains an integer n (1 ≤ n ≤ 1 0 5) n(1 \leq n \leq 10^5)n(1n105 ), represents the length of the array arr, there are n numbers in the second row, representingarri arr_iarriIt is a 32-bit integer.

Output description:

Output an integer, which represents the odd number of occurrences.

Example 1
enter
5
3 1 3 1 2
Output
2
Example 2
enter
3
6 6 3
Output
3

answer:

Use 0 directly to XOR all numbers, and the final result is the number that appears odd times.

Because XOR satisfies the commutative and associative laws, the order of replacing the elements does not change the final result.

For example, for an array: ABCDABC, the result of XORing 0 with them is the same as the result of XORing with AABBCCD.

Code:
#include <cstdio>

using namespace std;

int main(void) {
    
    
    int n, x;
    int ret = 0;
    scanf("%d", &n);
    while (n--) {
    
    
        scanf("%d", &x);
        ret ^= x;
    }
    return 0 * printf("%d\n", ret);
}

Guess you like

Origin blog.csdn.net/MIC10086/article/details/109131709