Before we wrote a function, written in a group of numbers have a number only appeared once, the other books have appeared 2 times, the idea is very simple, directly in turn or can find this number. See my previous blog post for details.
Then let's take a look at the present question.
The number of outputs in a group of 2 appears 1 times. Then the remaining number appeared 2.
Our idea of this problem is as follows:
1. Differences or results of different numbers
2. Find the number of digits in the XOR result that 1 appears.
3. Group XOR, when the occurrence of 1 of the bit XOR, not 1 of the bit XOR, the original array can be divided into 2 groups, and then different or will be able to get 2 only one occurrence of the number.
It's easy to understand the code:
#include <stdio.h>void getnumber (int *arry,int *numone, int *numsecound,int len) { int i = 0; int pivot = 0; int pos = 1; for (i = 0; i < len; i++) { pivot ^= * (arry+i); } while (!) ( pivot&1)) { pivot = pivot>>1; pos++; } for (i = 0; i<len;i++) { if ((* (arry+i) >>pos-1) & 1) { *numone ^ = * (arry+i); } else { *numsecound ^= * (arry+i); } }}int main () { int num1 = 0; int num2 = 0; int arry[] = {33,19,20,8,37,8,37,5,25,33,19,20}; getnumber (arry,&num1,&num2, sizeof (Arry)/sizeof (arry[0]); printf ( "%d ", NUM1); printf ( "%d", num2); return 0;}
This article from "Left Egg June" blog, reproduced please contact the author!
The "C language" output has 2 occurrences of 1 numbers in a set of numbers