[Xiaomi] ry number, ry number

Source: Internet
Author: User

[Xiaomi] ry number, ry number

In an integer array a with a length of n, all the other numbers appear twice except three digits. Write a program to output any number that appears only once. The smaller the time and space complexity of the program, the better. Example: a = {, 7}, output 4, 5, or 6.

Solutions
  • If only one occurrence occurs once, all the numbers are converted into an exclusive or operation and their values are returned.
  • If two numbers appear only once, for example, a and B, the result of an exclusive or operation on all numbers is x = a ^ B. Because a and B are not equal, x is not 0. Scan the first digit of 1 from the right to the left, and divide the original array into two groups based on whether the value is 1, and then process each group of data as needed.
  • If there are three numbers only once, you canThe three numbers are two-to-one or different, And the bitwise has two identical values..
Implementation Code
# Include <iostream> using namespace std; int lowbit (int x); int find (int * num, int len); int main () {int num [] = {1, 1, 2, 2, 3, 3, 4, 5, 6, 7}; cout <find (num, sizeof (num)/sizeof (num [0]) <endl; return 0 ;} // find the first position from right to left where 1 appears, int lowbit (int x) {return x &~ (X-1);} int find (int * num, int len) {int xors = 0; for (int I = 0; I <len; I ++) {xors ^ = num [I];} // The three numbers are two or two different, And the bitwise has two identical values, one different int low = 0; for (int I = 0; I <len; I ++) {// indicates low = lowbit (a ^ B) ^ lowbit (a ^ c) ^ lowbit (B ^ c) low ^ = lowbit (xors ^ num [I]);} int result = 0; for (int I = 0; I <len; I ++) {if (lowbit (xors ^ num [I]) = low) {result ^ = num [I] ;}} return result ;}

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.