Bits solution.

 DevX Home Today's Headlines   Articles Archive   Tip Bank   Forums

1. Registered User
Join Date
Sep 2004
Posts
2

## Bits solution.

import java.lang.*;

public class Bits
{
public static void main(String args[])
{
System.out.println("Hello there.");
for (int x=0; x<100; x++)
{
System.out.println("Bits to render " + x + "; " + minBits(x) + "\n");
}
}

private static int minBits(int _x)
{
if (_x == 0)
return 1;
else
return 1 + (int)Math.floor(Math.log((double)_x) / Math.log((double)2));
}
}

For a number system of base x, to determine the count of digits to represent a number you need the log(base x) of that number, rounded to the nearest whole number. So for any number, I need to calculate that number base 2. To calculate logs of any base, use
log(base b)X = log(base a)X / log(base a)b.

I think you need a bit to represent a zero, so minBits will return a 1 in that case.

2. Registered User
Join Date
Sep 2004
Posts
1

## min bits

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;
}
}```
there is surely a way of doing this using logical bitwise operators instead of logs - if any one wants to figure it out ;-)
Last edited by javelin; 10-05-2004 at 12:13 PM.

3. Registered User
Join Date
Oct 2004
Posts
1
I prefer my solution. It is same as "official" answer but more elegant.

public int minBits(int n) {
int x = 1;
while (n >> x++ > 0);
return x;
}

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•

 FAQ Latest Articles Java .NET XML Database Enterprise