Leetcode--single number

Source: Internet
Author: User

Title: Given An array of integers, every element appears twice except for one. Find the single one.

Note: This array is not said to be in a fixed order

Idea: Import java.util.Arrays;

public class Singlenum {
public int singlenumber (int[] nums) {
int r = 0;
for (int x:nums) {
r = r ^ x;  Here is the use of the XOR operation, which has two large characteristics: 1, a=0^a;
//2, a^b = B^a; Meet the Exchange law, then in the chaotic Order (1,2,3,4,3,2,1),
//Can be its first (1,1,2,2,3,3,4), then use the nature to do, return is;
}
return R;
}
}

When doing the problem, by the way Java's bitwise arithmetic logic to learn a bit, very feeling. It is summarized as follows:

1, XOR or operation: A^b, "The same is 0, the difference is 1".

Properties:

(1) The location of the a,b,p here is interchangeable !!! (same or also can)

(2) If you need to exchange the values of two variables, in addition to the usual use of the borrowed intermediate variables to exchange, you can also use XOR, only two variables to exchange , such as:a=a^b;  b=b^a;  a=a^b;(好用!)

(3) a:a^0 =a;

B:a ^b ^c = a ^ (b ^ c) = (a ^ b) ^ C; (Binding law)

c:a ^ b ^ a = b; (Transform position)

D:d = a ^ b^ C can be introduced a = d ^ b ^ C;

2, the same or operation (XOR non):! (a^b), "Same as 1, different for 0"

3, and (in series): A&&b,

4, or (parallel): a| | B

5, non (NO):!a,

Leetcode--single number

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.