only one time code appears in a numeric array (C)
This address: Http://blog.csdn.net/caroline_wendy
Title: In an integer array, except for two digits, the other numbers appear two times. Please tap the code to find the two numbers that appear only once.
Assuming that it is different from beginning to end or every number in the array, then the result is exactly the one that appears only once.
Based on the result array binary one is 1, in this grouping, 1 for a group, 0 for a group, and again for 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 & amp;& 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 ResU Ltexclusizeor = 0;for (int i=0; i<length; ++i) resultexclusizeor ^= data[i];size_t indexOf1 = FindFirstBitIs1 (resultexc Lusizeor) *num1 = *num2 = 0;for (int j=0; j<length; ++j) {if (IsBit1 (Data[j], indexOf1)) *num1 ^= data[j];else*num2 ^= D ATA[J];}} int main (void) {int data[] = {2, 4, 3, 6, 3, 2, 5, 5};int num1, num2; Findnumsapprearonce (data, 8, &NUM1, &num2);p rintf ("num1 =%d num2 =%d\n", NUM1, num2);}
Output:
NUM1 = 6 num2 = 4
Copyright notice: This article Bo Master original articles, blogs, without consent may not be reproduced.
Programming algorithm-Only one time code appears in a numeric array (C)