How to calculate the digits of a positive integer? Como calcular os dígitos de um inteiro 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. Eu apenas entrou em toda a necessidade de calcular os dígitos de um número. Soa trivial como podemos ver os dígitos e contar-los facilmente.
The challenge is how to find them (with least effort) computationally? O desafio é como encontrá-los (com menos esforço) computacionalmente?
Solution: Solução:
1 + (int) (Math.log(i) / base10) 1 + (int) (Math.log (i) / base10)
where base10 = Math.log(10) onde base10 = Math.log (10)
Filed under Arquivado em Java Software Java Software | |
| |
RSS 2.0 RSS 2,0 | |
Email this Article E-mail este artigo
You may also like to read Você pode também gosta de ler |





January 25th, 2004 at 6:16 am 25 de janeiro de 2004 em 6:16 am
Hmm. Did a search and found this. Fez uma pesquisa e descobrimos isso. 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. Se você é estritamente lidar com ints, parece que este método é o mais otimizado, uma vez que não requer qualquer método ou chamadas logorithmic computação. It performs at most 3 simple comparisons. Ela realiza, no máximo, 3 comparações simples.
/** / **
* Counts number decimal digits in a 32 bit signed number. * Counts número decimal dígitos em 32 bits assinou um 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 cujos algarismos que deseja contar. Must lie in range 0 .. Deve situar-se num intervalo de 0 ..
* Integer.MAX_VALUE; * Integer.MAX_VALUE;
*
* @return number of digits in x, eg Integer.toString(x).length() * @ Retorno número de dígitos em x, por exemplo, Integer.toString (x). Comprimento ()
* @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 / / Fazer uma pesquisa binária unravelled
if (x if (x