During the interview I had some time ago I was asked to calculate the number of positive (that is, set "1") bits in the structure of the bitvector (for example, an unsigned integer or long). My solution was pretty simple in C #:
int CountBits(uint input) { int reply = 0; uint dirac = 1; while(input != 0) { if ((input & dirac) > 0) reply++; input &= ~dirac; dirac<<=1; } return reply; }
Then I was asked to solve the problem without use without any shifts: neither explicit (for example, "<" or "→"), nor implicit (for example, multiplying by 2). The brute force solution using potential row 2 (for example, 0, 1, 2, 4, 8, 16, etc.) will not be the same.
Does anyone know such an algorithm?
As I understand it, this should be a kind of more or less general algorithm that does not depend on the size of the input bit vector. All other bitwise operations and any mathematical functions are allowed.
source share