Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding two consecutive 1's in a bitstring in less then n time?

I am trying to figure out a way to see if a bitstring has 2 consecutive ones in the bitstring size n in less then n time.

For example, lets say we had a bitstring size 5 (index 0-4). If index 1 and 3 were both 0's, I could return false. But if they were both ones then I may have to do 5 peeks to find my answer.

The bitstring doesn't have to be length 5. For simplicity's sake, lets say it can be between 3 and 8.

like image 927
EricP Avatar asked Dec 08 '22 00:12

EricP


1 Answers

Simplest solution might be to bitwise AND the original string with a version of itself which has been shifted left or right by 1 bit. If the resulting bit string in non-zero then you have at least one 11 in there:

test = (src & (src << 1));
like image 89
Paul R Avatar answered May 10 '23 22:05

Paul R