How to calculate the digits of a positive integer?

By Angsuman Chakraborty, Gaea News Network
Sunday, January 25, 2004

I just came across the need to calculate the digits of a number. It sounds trivial as we can see the digits & count them easily.
The challenge is how to find them (with least effort) computationally?

Solution:

1 + (int) (Math.log(i) / base10)

where base10 = Math.log(10)

Filed under: Java Software
Discussion

sonnykwe
January 29, 2010: 12:11 pm

Paul, Math.log(10) = 2.30, this method is a natural logarithm funtion.


Paul J
November 25, 2009: 1:30 am

Math.log(10) = 1 anyway, so could be left out


Kevin
September 17, 2009: 1:09 am

It doesnt seem to work when I enter a 7 digit number, I get a cound of 6.

It works on 6 digits and 8 digits but not 7. Probably more errors with other values as well..

July 23, 2009: 8:53 pm

@Min the issue with this approach is you have to explicitly set the bounds. This is fine for base 10, but what about base 2? One can represent a pretty long binary number in a “long” datatype.

@Absar String operations are much expensive than numerical operations. Also, this does not take into account other bases (though it could, by using a STRING->NBASE function).

April 27, 2009: 8:06 am

int n = 12345;
String s = String.valueOf(n);
int counted = s.length();

:D


Min
January 25, 2004: 6:16 am

Hmm. Did a search and found this. http://mindprod.com/jgloss/widthindigits.html
If you are strictly dealing with ints, it seems like this method is the most optimized as it doesn’t require any method calls or logorithmic computation. It performs at most 3 simple comparisons.

/**
* Counts number decimal digits in a 32 bit signed number. 0 => 1, 9 => 1,
* 99 => 2, 2,147,483,647 => 10
*
* @param x
* number whose digits you wish to count. Must lie in range 0 ..
* Integer.MAX_VALUE;
*
* @return number of digits in x, e.g. Integer.toString(x).length()
* @author Marc Chappuis marnic@ludomedia.ch
*/
public static int widthInDigits(int x) {
// do an unravelled binary search
if (x

YOUR VIEW POINT
NAME : (REQUIRED)
MAIL : (REQUIRED)
will not be displayed
WEBSITE : (OPTIONAL)
YOUR
COMMENT :