Application of XOR in algorithm

Source: Internet
Author: User

XOR, as the name implies, the same take 0, different take 1, XOR or operation has a binding law. There are two classic applications on the algorithm, one is to exchange two numbers, and the other is to find out the number of single-drop.

1. Exchange values for two variables

Unlike other languages, the C and C + + languages differ or do not have XOR, but instead use "^" and type as shift+6. (While the "^" in other languages generally denotes a exponentiation), if you need to exchange the values of two variables, in addition to the commonly used borrowing intermediate variables to exchange, you can also use XOR, only two variables to exchange, such as:

1 2 3 A=a^b; B=b^a; A=a^b;
Detailed
1 2 3 A1=a^b b=a1^b a=a1^b=a1^ (a1^b) =a1^a1^b=b
Attention:
1 a=a^b^ (B=a); This type of form is incorrect for UB behavior and will have different results in different compilers, do not use
This completes the exchange of A and B. All in all: the same variable and another variable and its XOR value are different or equal to itself.

2. Single count (one drop, 2 orders):

Requires time complexity O (n), Spatial complexity O (1). To say a few words about complexity:

O (n) Such a sign is called asymptotic time complexity, which is an approximation. The order of the various asymptotic complexity from small to large is as follows

O (1) < O (Logn) < O (n) < O (Nlogn) < O (n^2) < O (n^3) < O (2^n) < O (n!) < O (n^n) The first idea is to go ahead and Traverse looking. The time complexity is O (Nlogn), and the spatial complexity is O (logn).

The second idea is to use a hash table, the time complexity is O (n), and the spatial complexity is O (n).

The third method is to use the combination of the law of the XOR operation can be, which involves the extension of the topic, if the 22 pairs of elements adjacent to the direct XOR, if it is scattered, then the first fast and then different or.

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.