Number of occurrences in the number is K, but one is not K.

Source: Internet
Author: User

Idea: 1. Create an auxiliary array arr [32] and count the sum of 1 in the corresponding bits of the number in the array

2. if the number to be searched is not 0 on a certain bit of I, the modulo of K in arr [I] is certainly 0; otherwise, the number to be searched is 1 in this bit, S + = 1 <I

The Code is as follows:

Int find (int * a, int Len, int K) {int arr [32] = {0}; int I, j; for (I = 0; I <Len; ++ I) {unsiged int K = A [I]; --> the negative value is shifted to 1, and an error occurs. Therefore, it first becomes unsigned int for (j = 0; j <32; ++ J) {arr [J] + = (k> J) & 1); // calculate the number of 1 in an integer} int result = 0; for (j = 0; j <31; ++ J) // calculates the value {If (ARR [J] % K! = 0) Result + = (1 <j);} If (ARR [31] % K! = 0) // signed result = 0-result; return result ;}


--> Question Deformation:

1. The number of one group is 4 K + 2, and the number of one group appears only twice, and the number of others appears 4 times. Find this number --> directly call the above Algorithm

2. Two numbers in an array appear only once, and the other numbers appear twice. Find the two numbers:

1. returns the result of an exclusive number or number of arrays.

2. Find the first bit of 1 from the number of results of an exclusive or, you can see that the two numbers to be searched must be 0 and 1 in this bit,

3. Based on this bit, the array is divided into two groups. One group has 0 bits and the other has 1 bits. Then, all the values in the two groups are different or. The result is displayed.


Number of occurrences in the number is K, but one is not K.

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.