same basic solution as brismith though I personally don't like seeing more than 1 return statement in a method
this solution doesn't work for negative numbers (since logs don't work on them) - the number of bits for negative numbers is a different problem because of the sign bit etc.
the <n> param should be unsigned long instead of int - thus eliminating the negative problem and increasing the domain (possible values) of n
0>n<1000000 is way too small for pratical use since it is less than 1 megabyte - yes I know it's just the assigned constraint ;-)
if a signed int is used as the <n> parameter exception handling should be applied to the <if> block to ensure code safety in case a negative is passed
Code:
// C# code
using System;
class Bits
{
public Bits() {}
public static int minBits(int n)
{
int bits = 1; // n is 0 or 1
if( n > 1 )
bits = (int)(System.Math.Log(n)/System.Math.Log(2)) + 1;
return bits;
}
}
Comments:
there is surely a way of doing this using logical bitwise operators instead of logs - if any one wants to figure it out ;-)
Bookmarks