Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bit operation question

Tags:

bit

Is there a way to find the bit that has been set the least amount of times from using only bit operations?

For example, if I have three bit arrays:

11011001

11100000  
11101101

the bits in position 3 and 5 are set to 1 in only 1 of the three vectors.

I currently have an o(n) solution where n is the number of bits in the bitarray, where I go through each bit in the bitarray and increment each time there is a 1, but for some reason I think there is a o(1) solution that I can use with few bitwise operations. Can anyone advise? Thanks.

like image 783
dustin ledezma Avatar asked Jun 05 '11 01:06

dustin ledezma


People also ask

Is bit manipulation asked in interview?

Is Bit Manipulation Important during Interviews? Yes. The interviewer might not ask direct questions on bit manipulation but can ask problems which are related to bit manipulation like bitmask dp , number of subsets etc.

How does bit operation work?

A bitwise operation operates on two-bit patterns of equal lengths by positionally matching their individual bits. For example, a logical AND (&) of each bit pair results in a 1 if both the first AND second bits are 1. If only one bit is a 1, the result is 0.

Why is bit operations faster?

Basically, you use them due to size and speed considerations. Bitwise operations are incredibly simple and thus usually faster than arithmetic operations. For example to get the green portion of an rgb value, the arithmetic approach is (rgb / 256) % 256 .

Which is not a bitwise operator Question & << &&?

1) Which is not a bitwise operator? && is not a bitwise operator. It is a Logical AND operator, which is used to check set of conditions (more than one condition) together, if all conditions are true it will return 1 else it will return 0.


2 Answers

You can use a duplicate/shift/mask approach to separate the bits and maybe be a little faster than an iterative bit shift scheme, if the total number of values is limited.

Eg for each "bits" 8-bit value, assuming no more than 15 values:

bits1 = (bits >> 3) & 0x11;
bits2 = (bits >> 2) & 0x11;
bits3 = (bits >> 1) & 0x11;
bits4 = bits & 0x11;
bitsSum1 += bits1;
bitsSum2 += bits2;
bitsSum3 += bits3;
bitsSum4 += bits4;

Then, at the end, break each bitsSumN value into two 4-bit counts.

like image 85
Hot Licks Avatar answered Sep 30 '22 13:09

Hot Licks


Another option is to reflect the bit array. In your example:

111
111
011
100
101
001
000
101

And then use the standard bit counting methods to count the number of bits set.

Doing this naively would most likely be slower than the normal approach, but you could try to adjust the algorithms to pull the bits from different words instead of the techniques they use. The fastest techniques look at multiple bits at a time, though, so would seemingly be difficult to optimize in your case.

like image 20
Seth Robertson Avatar answered Sep 30 '22 14:09

Seth Robertson