XOR operation in C + + ^

Source: Internet
Author: User

Make good use of the different or can produce wonderful effects.

The nature of an XOR operation:

no matter what a number different or it itself equals 0 . Other words. Assuming we are different from beginning to end or each number in the array, then the result is exactly the one that appears only once. Because those appeared two times the number all was offset off in XOR.

Examples:

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



Since 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 XOR. The number of two occurrences is exactly different 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: An integer array with the exception of two digits. The rest of the numbers have appeared two times. Please tap the code to find the two numbers that appear only once. 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/

References:

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

Http://blog.csdn.net/caopengcs/article/category/1502799/4

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.