Reputation: 2901
I came across such a programming interview question. But it is not obvious to me how you know bit shift can be used here. Someone kindly explain. Thanks.
An array is of size N with integers between 0 and 1024(repetitions allowed). Another array of integers is of size M with no constraints on the numbers. Find which elements of first array are present in the second array. (If you are using extra memory, think of minimizing that still, using bitwise operators)
I would like to know what in the real world the bitshift operators mean. And how to identify the problems that require a bitshift approach.
Thanks Sanjay
Upvotes: 3
Views: 1927
Reputation: 106096
It's a very easy interview question really. Because you know there's at most 1025 distinct integers in the first set, you can use that number of bits to represent whether each of those numbers is found or not in input sets. So, if you want the answer to print each distinct number exactly once, the logic is:
Now, to create a bitset of 1025 bits might not be supported directly by your language, so what you sometimes have to do is use an array of bytes, each of which has 8 bits. Then, say you want to set bit "k", you'll find the byte at index k / 8, then set the bit at position k % 8. To do the latter, you have to convert from a bit position (0 through 7) to a bit value (bit 0 represents value 1, bit 1 value 2, bit 2 value 4... bit 7 value 128 - all the powers of two). To get these values, you take the number 1 and bitshift it left by the "bit position". So, 1 << 0 is still 1, while 1 << 7 is 128. You can then:
if (array[k / 8] & (1 << (k % 8))) ...it's on...
array[k / 8] |= (1 << (k % 8));
There are more efficient ways to do this if there happens to be a lot less than 1025 values in either set, but this is a good general solution.
Upvotes: 5
Reputation: 2397
Bitshift operators work like this. Imagine you have an integer value X. This X will be represented in Binary form , which is 1 and 0's. After words according to the shift operator. Number of positions will be moved.
Visit this link http://www.php.net/manual/en/language.operators.bitwise.php they have some examples on how this shift operators work.
Upvotes: 1