Only two digits in an array appear once, and all other numbers appear two times. Find these two numbers.

Source: Internet
Author: User

From beginning to end, or every number in an array, the result is an XOR result of two occurrences of a single number. Because the other numbers appear two times, they all cancel out in the XOR. Since these two numbers are definitely different, the XOR result is definitely not 0, meaning that at least one of the binary representations of the result number is 1. We find the position of the first 1 bit in the result number, which is recorded as the nth bit. Now we divide the numbers in the original array into two sub-arrays with the nth bit not 1, and the nth bit for each number in the first Subarray is 1, and the nth bit for each number of the second subarray is 0.

 #include <stdio.h> #include <stdlib.h> void find (int a[], int sz) {int i = 0;
    int NUM1 = 0;
    int num2 = 0;
    int num = 0;
    int flag = 0;
    for (i = 0; i < sz; i++) {num = num^a[i];
            } for (i = 0; i <; i++) {if ((num >> i) & 1)! = 1)//The position of the first 1 in the binary number of this number is {
        flag++;

    } else break;
        } for (i = 0; i < sz; i++) {if (((A[i] >> flag) &1) = = 1)//divided into 2 groups num1 ^= a[i];
    else num2 ^= A[i];
} printf ("%d%d\n", num1,num2);
    } int main () {int a[] = {1, 2, 2, 3};
    int sz = sizeof (a)/sizeof (a[0]);
    Find (A, SZ);
    System ("pause");
return 0; }

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.