Programming algorithm-Only one time code appears in a numeric array (C)

Source: Internet
Author: User

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, &AMP;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)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.