How to calculate the digits of a positive integer? Cómo calcular los dígitos de un número entero positivo?
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. Me encontré con la necesidad de calcular los dígitos de un número. Suena trivial como podemos ver los dígitos y contar con ellos fácilmente.
The challenge is how to find them (with least effort) computationally? El reto es encontrar la manera de ellos (con menos esfuerzo) computacionalmente?
Solution: Solución:
1 + (int) (Math.log(i) / base10) 1 + (int) (Math.log (i) / base10)
where base10 = Math.log(10) donde base10 = Math.log (10)
Filed under Filed under Java Software El software de Java | |
| |
RSS 2.0 RSS 2,0 | |
Email this Article Enviar artículo
You may also like to read También puede leer |





January 25th, 2004 at 6:16 am 25 de enero de 2004 a las 6:16 am
Hmm. Did a search and found this. ¿Hubo algún hecho en la búsqueda y encontré este. 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. Si se trata estrictamente con ints, parece que este método es el más optimizado, ya que no requiere ningún método de llamadas o logorithmic cómputo. It performs at most 3 simple comparisons. Se realiza en la mayoría de las comparaciones simples 3.
/** / **
* Counts number decimal digits in a 32 bit signed number. * Número de Cuenta dígitos decimales en un 32 bits firmado número. 0 => 1, 9 => 1, 0 => 1, 9 => 1,
* 99 => 2, 2,147,483,647 => 10 * 99 => 2, 2.147.483.647 => 10
*
* @param x * @ Param x
* number whose digits you wish to count. * Número de cuyos dígitos que desea contar. Must lie in range 0 .. Deberá situarse en el rango 0 ..
* Integer.MAX_VALUE; * Integer.MAX_VALUE;
*
* @return number of digits in x, eg Integer.toString(x).length() * @ Regresar número de dígitos en x, por ejemplo, Integer.toString (x). Longitud ()
* @author Marc Chappuis * @ Autor Marc Chappuis marnic@ludomedia.ch
*/ * /
public static int widthInDigits(int x) { public static int widthInDigits (int x) (
// do an unravelled binary search / / Realizar una búsqueda binaria unravelled
if (x si (x