An array has only one occurrence in addition to two elements, all of the other elements appear two times, please find only one occurrence of the two elements, and output

Source: Internet
Author: User
#include <stdio.h>
#define N 10
int main ()
{
int A[n] = {1,2,7,99,3,3,4,1,2,4}, Flat[n] = {0};
int I, j, sum = a[0], last_bit = 0, SUM0 = 0, sum1 = 0;
To vary or manipulate all elements in an array
If only one element of an array appears once, the result of an XOR is that the element appears only once
for (i = 1; i < N; i + +)
{
sum = sum ^ (a[i]);
}
If there are two elements in the array that occur only once, the result of the above XOR is converted to binary and judged from right to left, and the first position of 1 is recorded as I
for (i = 0; Last_bit! = 1; i + +)
{
Last_bit = sum & 1;
sum = sum >> 1;
}
The second bit of the binary form of all the elements is then scanned, and the results are recorded in the flat array
The flat[j]=1 indicates that the first bit of the J element is 1, otherwise 0
for (j = 0; J < N; J + +)
{
FLAT[J] = (A[j] >> (i-1)) & 1;
}
Group all elements according to the flat array obtained from the above loop
The result is 1 of the different or operation together, for 0 of the different or operation, two sets of different or the result is two appear only once the element
for (j = 0; J < N; J + +)
{
(Flat[j] = = 1)? (sum1 = sum1 ^ (a[j])): (SUM0 = sum0 ^ (a[j]));
}
printf ("%d%d\n", SUM0, SUM1);
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.