Topic:
In an array of integers, except for two digits, the other numbers appear two times. Please write the program to find the two only occurrences of the number.
Ideas:
(1) First consider the array if only one number appears once, the other is two times the case, in this case, will all
Numbers are bitwise XOR (^), because the same number is different or the result is 0, so the final result is the number that appears once.
(2) The following considerations appear that there are two appear once, the other is appearing once, in this case, can be all the XOR again,
Then the final result is an XOR result of the number of occurrences of the two.
And then find this number from right to 0 number of the first not 0 bits, so you can according to this bit the array into two parts, part
This nth bit is 0, and part of the nth bit is 1.
And then different or, finally, the two results are.
1#include <iostream>2#include <vector>3 using namespacestd;4 5 //find this number in the right-hand section not for 0.6 intNumber_of_first_one (unsignedinta)7 {8 intRe=0;9 for(intI=0;i< +; i++)Ten { One if((a& (1<<i))! =0) A{re=i; Break;} - } - returnre; the } - - //determines whether the nth bit on the right is 1 - BOOLIfone (unsignedintAintN) + { - if(a& (1<<N)) + return 1; A Else at return 0; - } - - //The main function. - voidFind_number (vector<int>& VEC,int*NUM1,int*num2) - { in if(Vec.empty ()) - return; to intlen=vec.size (); + if(len<=1) - return; the *Unsignedinta=vec[0]; $ for(intI=1; i<len;i++)Panax Notoginsenga^=Vec[i]; - the intn=Number_of_first_one (a); +*num1=0; A*num2=0; the for(intI=0; i<len;i++) + { - if(Ifone (vec[i],n)) $*num1^=Vec[i]; $ Else -*num2^=Vec[i]; - } the } - intMain ()Wuyi { the intary[8]={2,4,3,6,3,2,5,5}; -vector<int> Vec (ary,ary+8); Wu intNUM1; - intnum2; AboutFind_number (vec,&num1,&num2); $cout<<num1<<Endl; -cout<<num2<<Endl; -System"Pause"); -}
The sword refers to the offer--. Question 40: A number that appears only once in an array