XOR operation in C + + ^

Source: Internet
Author: User

Good use of the different or can produce magical effects.

The nature of an XOR operation:

any one number XOR or it is equal to 0 . That is, if we vary from start to finish or every number in the array, the final result is exactly the one that appears only once, because those numbers that appear two times are all offset by XOR.

Examples:

The given size is an array of N, the elements in the array are not duplicated, the element size range is 1~ (n+1), the goal is to find the number of the first miss. The time complexity of O (N) is required, and the space is O (1).



Because this array has only N elements in total, there must be a number in the 1--n+1 that does not exist. Set res = 0, using XOR or operation, first let res and subscript +1 xor, then with each number of different or. The number that appears two times is exactly the same or 0. The rest is the result.

<span style= "FONT-SIZE:14PX;"  >//You can also with includes, for example://#include <algorithm>int solution (vector<int> &a) {    // Write your code in c++98    int res = 0;    int max = A.size ();    if (max==0) {        return 1;    }    for (int i=0;i<a.size (); i++) {        res^= (i+1);        if (A[i]<=max) {            res^=a[i];        }    }    return res==0?max+1:res;} </span>

A similar other question:

title: In an integer array, except for two digits, the other numbers appear two times. Please write the program to find the two only occurrences of the number. The required time complexity is o (n), and the spatial complexity is O (1).

See the answer: http://zhedahht.blog.163.com/blog/static/2541117420071128950682/

Reference documents:

Http://www.cnblogs.com/parapax/p/3632255.html

XOR operation in C + + ^

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.