I had the following question in an interview, and I suppose I gave a working implementation, but I was wondering if there was a better implementation that was faster, or just a trick I missed.
Given 3 unsigned 30-bit integers, return the number of 30-bit integers that, compared to any of the source numbers, have the same position bits set to 1. This we list all 0s
Let me give you an example, but for clarity, let's use 4bit.
Given:
A = 1001 B = 0011 C = 0110
It should return 8, since there are 8 4-bit ints in the set. Set:
0011 0110 0111 1001 1011 1101 1110 1111
Now, as I worked, I needed to take each number and list a lot of possibilities, and then count all the individual values. As I enumerated the set, to start with the number, add it to it, and then OR take it with me until I get to the mask. With the number itself in the set and the mask (all set to 1) also in the set. For example, to list a set of 1001:
1001 = the start 1011 = (1001 + 1) | 1001 1101 = (1011 + 1) | 1001 1111 = (1101 + 1) | 1001 (this is the last value as we have reached our mask)
So do this for each number, and then count uniques.
This is it in python code (but the language does not matter as long as you can perform bitwise operations, so why this question is flagged for c / C ++):
MASK = 0x3FFFFFFF def count_anded_bitmasks( A, B, C ): andSets = set( enumerate_all_subsets(A) + enumerate_all_subsets(B) + enumerate_all_subsets(C) ) return len(andSets) def enumerate_all_subsets( d ): andSet = [] n = d while n != MASK: andSet.append(n) n = (n + 1) | d andSet.append(n) return andSet
Now it works and gives the correct answer, but I wonder if I missed the trick. Since the question was to ask the score and not list all the values, perhaps there is a much faster way. Either by combining the numbers first, or by getting an invoice without transfer. I have a feeling. Since numbers containing many zeros, the enumeration grows exponentially, and this can take quite a while.
If you have AB and C, count a set of numbers with bits set to 1, where A or B or C have corresponding bits set to 1.
Some people do not understand the question (they did not help, so I did not ask it correctly, the first of them). Let us use the above values ββof AB and C:
A:
1001 1011 1101 1111
IN:
0011 0111 1011 1111
FROM
0110 0111 1110 1111
Now combine these sets and count the individual records. This is the answer. Is there a way to do this without listing the values?
Edit: Sorry for the error. Fixed.