Advantages of bitwise exclusive or operations

Source: Internet
Author: User

The previous log talked about bit operations.

 

Bit operators:

(1 ),~ Reverse retrieval ~ 0011 = 1100

(2), & bits and 0011 & 0110 = 0010

(3), | bit or 0011 | 0110 = 0111

(4) ^ exclusive or 0011 ^ 0110 = 0101

 

 

There are two questions about the advantages of bitwise OR (^) operations:

1. An array with a known length of 2n + 1. Each number in the array appears twice. Only one number X is unique. Find the separate number X?

First, let's talk about some knowledge points: a ^ A = 0; 0 ^ x = X;

Therefore, the solution is to perform an exclusive or operation on all the numbers in the array. A1 ^ A2 · x · = 0 ^ x = X;

 

2. An array a [10000] is known, and a number X is taken from it. Then, B [9999] is obtained, and the value of X is calculated?SpaceThe complexity requirement is O (1 ).

Solution:

A1 ^ A2 · a10000 = b1 ^ B2 · b9999 ^ X;

A1 ^ A2 · a10000 ^ B1 ^ B2 · b9999 = b1 ^ B2 · b9999 ^ x ^ B1 ^ B2 · b9999 = 0 ^ x = x;

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.