All the numbers in an array are paired. Only one or two numbers are separate, and this number is calculated

Source: Internet
Author: User

If there is only one number, then we can use the bitwise OR (^) to get, the code is as follows:

#include <stdio.h>int main () {int arr[] = {1, 1, 2, 2, 3, 3, 4};int size = sizeof (arr)/sizeof (int); int num = 0;for (int i = 0; i < size; i++) {num ^= arr[i];} printf ("%d\n", num); system ("pause"); return 0;}

If it is two numbers, then we can split the array, and then respectively with 0 or, its split thought is the array of all the number of all or, the resulting result is the two individual occurrences of the same or the result, because or its nature is the same as 0, different 1, So the number of each of the 1 bits is its different bits, we can find it first for 1 of the bit to mark, the same or together for one, 0 or together, the result is two numbers, the implementation code is as follows:

#include <stdio.h>void find_num (int *arr, int size)//Its implementation function is encapsulated, because is to return two values, C language                                          //realize the two values are printed out {int num1 = 0;int num2 = 0;int end_num = 0; int flag = 0;for  (int i = 0; i < size; i++) {End_num  ^= * (arr + i);} while  (! ( end_num & 1)) {flag++;end_num >>= 1;} for  (int i = 0; i < size; i++) {Int tmp = arr[i]  >> flag;if  (tmp & 1) {num1 ^= arr[i];} Else{num2 ^= arr[i];}} printf ("num1=%d\nnum2=%d\n",  num1, num2);} Int main ()//validation phase {Int arr[] = { 1, 1,&nbsP;2, 2, 3, 3, 4, 5 };int size = sizeof (arr)  / sizeof ( Arr[0]); Find_num (arr,size); System ("pause"); return 0;}

If there is anything wrong, hope to criticize

This article is from the "Pawnsir It Road" blog, so be sure to keep this source http://10743407.blog.51cto.com/10733407/1713119

All the numbers in an array are paired. Only one or two numbers are separate, and this number is calculated

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.