Here\'s a tough one(atleast i had a hard time :P):
find the index of the highest bit set of a 32-bit number without using any loops.
Paislee's solution is actually pretty easy to make tail-recursive, though, it's a much slower solution than the suggested floor(log2(n));
int firstset_tr(int bits, int final_dec) {
// pass in 0 for final_dec on first call, or use a helper function
if (bits & 0x80000000) {
return 31-final_dec;
} else {
return firstset_tr( ((bits << 1) | 1), final_dec+1 );
}
}
This function also works for other bit sizes, just change the check, e.g.
if (bits & 0x80) { // for 8-bit
return 7-final_dec;
}