The numeric code that appears only once in the array (c)
Address: http://blog.csdn.net/caroline_wendy
Question: except two numbers in an integer array, the other numbers appear twice. Please write a program to find the numbers that appear only once.
If each number in the array is exclusive from start to end, the final result is the number that appears only once.
Based on the result array, a binary value of 1 is used as the Group, a group of 1, a group of 0, and then returns the XOR. Finally, two results are obtained.
Time complexity O (n ).
Code:
/* * main.cpp * * Created on: 2014.6.12 * Author: Spike *//*eclipse cdt, gcc 4.8.1*/#include <stdio.h>#include <stdlib.h>#include <string.h>size_t FindFirstBitIs1(int num) {size_t indexBit = 0;while ((num&1)==0 && indexBit<(8*sizeof(int))) {num >>= 1;++indexBit;}return indexBit;}bool IsBit1(int num, size_t indexBit) {num >>= indexBit;return (num&1);}void FindNumsApprearOnce(int data[], int length, int* num1, int* num2) {if (data == NULL || length <= 0)return;int resultExclusizeOR = 0;for (int i=0; i<length; ++i)resultExclusizeOR ^= data[i];size_t indexOf1 = FindFirstBitIs1(resultExclusizeOR);*num1 = *num2 = 0;for (int j=0; j<length; ++j) {if (IsBit1(data[j], indexOf1))*num1 ^= data[j];else*num2 ^= data[j];}}int main(void){int data[] = {2, 4, 3, 6, 3, 2, 5, 5};int num1, num2;FindNumsApprearOnce(data, 8, &num1, &num2);printf("num1 = %d num2 = %d\n", num1, num2);}
Output:
num1 = 6 num2 = 4