Interview Question
Software Engineer / DevelopersIf I am not wrong we need t count the number of bits that are set in the mantissa part + 1 for finding the bits set in the floating point number?
Brian Kernighan's method goes through as many iterations as there are set bits. So if we have a 32-bit word with only the high bit set, then it will only go once through the loop.
Published in 1988, the C Programming Language 2nd Ed. (by Brian W. Kernighan and Dennis M. Ritchie) mentions this in exercise 2-9. On April 19, 2006 Don Knuth pointed out to him that this method "was first published by Peter Wegner in CACM 3 (1960), 322. (Also discovered independently by Derrick Lehmer and published in 1964 in a book edited by Beckenbach.)"
long count_bits(long n) {
unsigned int c; // c accumulates the total bits set in v
for (c = 0; n; c++)
n &= n - 1; // clear the least significant bit set
return c;
}
Here, no of bits set in the memory layout is what we need, right? We could use a union as below:
#include <stdio.h>
int main()
{
union u {
float num;
int i;
} u1;
u1.num = 0.15625; /* floating number to check */
int num_bits = 0;
while (u1.i) {
num_bits++;
u1.i = u1.i & (u1.i-1);
}
printf("No of bits is %d\n", num_bits);
}
Wouldnt this do?
Is the representation of floating point number given? for example IEEE754
- ftfish July 10, 2010If so, just count. If not, unsolvable.