I've written a function trailing_zeroes(int n) that returns the number of the trailing zeroes in the binary representation of a number.
Example: 4
in binary is 100
, so the function in this case returns 2
.
unsigned trailing_zeroes(int n) {
unsigned bits;
bits = 0;
while (n >= 0 && !(n & 01)) {
++bits;
if (n != 0)
n >>= 1;
else
break;
}
return bits;
}
The reason of the if
statement is because in case n
equals to 0, there will be a loop.
I think it's pretty ugly this code written like this; is there a better way?
I want to avoid the break
statement inside the while
, because a lot of people told me that using that statement inside while/for
sometimes could be "informal". I thought to rewrite the function like this, but I don't think it's the best way to do it:
unsigned bits;
if (n == 0)
return bits = 1;
bits = 0;
while (!(n & 01)) {
++bits;
n >>= 1;
}