Consider an arbitrary binary vector of dimension n. For n=4, an example vector might be 1100.
For such a vector, I'd like to know the top-most position whose bit has the value of 1. For the 1100 example above, I'd like to get the answer 4 (counting from the right).
A recursive O(log(n)) solution (more or less binary search) for the example case above is
- Start with 1100
- Split down the middle into two 2-bit vectors 11 and 00
- Is the first of these greater than zero? Yes it is, so we focus now only on the first 2-bit vector (i.e. we know that our position answer can't be 1 or 2...it must be 3 or 4)
- Split 11 into two 1-bit vectors 1 and 1
- Is the first of these greater than zero? Yes, and it's also 1-bit long. We know that this is our position, so we return it.
My question: Assuming in a practical setting that 1) n is not greater than the word size on a general-purpse computer (i.e. n<=64), and 2) that we're given the "common" general-purpose instruction set, is there any way to do this in O(1) operations (worst case) with respect to the size of the vector instead of O(log(n))? I'm quietly hoping that there might be some combination of bitwise instructions that one could exploit, although my hopes are not high :(.
Note: using some kind of static structure which maps each possible vector to a result is not practical (would require too much memory for e.g. the n=64 case).