Programming Algorithm-numeric code that appears only once in an array (c)

Source: Internet
Author: User
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








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.