Topic:
Given a group of numbers, only two numbers appear once, and all the other numbers are paired. How to find these two numbers. Write a function implementation.
Topic Analysis:
last time, for a group of numbers only one number appears once, all the other numbers are paired, we use the entire array element is different or, but to find out two occurrences of the number should be how to solve it? First of all the elements are different or, the result is two occurrences of the number of the difference or result, and then convert the result to binary, find the first 1 of the binary number, and then according to the judgment of the 1 group, divided into two groups, respectively, the elements of two groups all different or, then find two different numbers.
For example: The elements in the array are the following numbers:
0000--0
0000--0
0001--1
0001--1
0010--2
0011--3
0011--3
0100--4
0100--4
0101--5
The result of all elements is: 0111 with the last surface of 1 as the condition, divided into the first group (1, 1, 3, 3, 5) and the second group (0, 0, 2, 4, 4), respectively, the two groups of elements are all different or.
Here are the specific procedures:
#define _CRT_SECURE_NO_WARNINGS 1#include <stdio.h> #include <stdlib.h> Int find_get (Int num) //converted to binary { int get = 0; while (num) { if (num % 2 == 1) //returns the number of digits in the binary of the transformation that appears first { return get; } get++; num = num / 2; }return -1;} void find_num (INT&NBSP;ARR[],&NBSP;INT&NBSP;RET,&NBSP;INT&NBSP;*P,&NBSP;INT&NBSP;*Q) { int i = 0; int fiNd = 0; int pos = 0; for (i = 0; i < ret; i++) //will all the numbers XOR, get find { find ^= arr[i]; } pos = find_get (find); for (i = 0; i < ret; i++) { if (1 & (arr[i] >> pos)) { *p ^= arr[i]; } else { *q ^= arr[i]; } }} int main () { int arr[] = { 1,1,2,2,3,3,4,5}; int ret = sizeof (arr) / sizeof (arr[0]) ; int find = 0; int num1 = 0; int num2 = 0; printf (" Output only one occurrence of the number: \ n "); find_num (arr, ret, &num1, &num2); printf ("%d %d", num1, num2); System ("pause"); return 0; }
This article from "Unintentional persistent" blog, reproduced please contact the author!
Find the two numbers that appear only once in a set of numbers, and all the other numbers appear in pairs.