Original link:
Http://blog.sina.com.cn/s/blog_a53544e0010146nv.html
XOR Operation ^. is a very important bit operation.
To put it simply:
0^0=0
1^0=1
1^1=0
and a a^0=a a^a=0.
and B^a^a=b because b^a^a=b^ (a^a) =b^0=b
And then we can use him to exchange the value of AB.
A^=b
B^=a
A^=b
Application Distance:
1-1000 is placed in an array of 1001 elements, and only one element value is duplicated, and the others appear only
A. Each array element can only be accessed once, and an algorithm is designed to find it; no secondary storage empty
, can you design an algorithm implementation?
Solution One, it is obvious that someone has proposed a more wonderful solution, adding up all the numbers, minus the 1+2+...+1000.
This algorithm is perfect enough to believe that the answer to the question is the algorithm, the only problem is that if the sequence is too large, it may lead to overflow.
Solution Two, XOR is not the problem, and performance is better.
All the numbers are different or, the results obtained are different from the results of the 1^2^3^...^1000, and the result is the number of repetitions.
But although this algorithm is very simple, it is not an easy thing to prove. This is related to several characteristics of the XOR operation.
The first is that the XOR algorithm satisfies the commutative law and the binding law.
So, 1^2^...^n^...^n^...^1000, regardless of where these two n appear, can be converted into the form of 1^2^...^1000^ (n^n).
Second, for any number x, there are x^x=0,x^0=x.
So 1^2^...^n^...^n^...^1000 = 1^2^...^1000^ (n^n) = 1^2^...^1000^0 = 1^2^...^1000 (that is, the XOR of all the numbers except n in the sequence).
The result of 1^2^...^1000 (n is not included in the sequence) is T
The result of 1^2^...^1000 (which contains n in the sequence) is t^n.
t^ (t^n) =n.
So, all the numbers are different or, the results obtained are different from the results of 1^2^3^...^1000, and the result is a repetition number.
Of course, some people will say, 1+2+...+1000 results have Gaussian law can be quickly calculated, but in fact 1^2^...^1000 results are also regular, the algorithm is more simple than the Gauss law.
The nature of a different or