How to calculate the digits of a positive integer? Come calcolare le cifre di un numero intero 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. Ho appena trovato la necessità di calcolare le cifre di un numero. Sembra banale come si può vedere le cifre & count facilmente.
The challenge is how to find them (with least effort) computationally? La sfida è come trovare loro (con meno sforzo) computazionalmente?
Solution: Soluzione:
1 + (int) (Math.log(i) / base10) 1 + (int) (Math.log (i) / Base10)
where base10 = Math.log(10) dove Base10 = Math.log (10)
Filed under Elencato sotto Java Software Software Java | |
| |
RSS 2.0 RSS 2,0 | |
Email this Article Invia questo articolo
You may also like to read Si può anche leggere come |





January 25th, 2004 at 6:16 am 25 gennaio 2004 alle 6:16 am
Hmm. Did a search and found this. Ha fatto una ricerca e trovato questo. 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 si sono rigorosamente si occupano di ints, sembra che questo metodo è il più ottimizzato in quanto non richiede alcun metodo di chiamate o logorithmic calcolo. It performs at most 3 simple comparisons. Svolge la maggior parte a 3 semplici raffronti.
/** / **
* Counts number decimal digits in a 32 bit signed number. * Conti numero cifre decimali in una a 32 bit firmato numero. 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. * Numero di cifre di cui si desidera contare. Must lie in range 0 .. Deve trovarsi nel raggio di portata 0 ..
* Integer.MAX_VALUE; * Integer.MAX_VALUE;
*
* @return number of digits in x, eg Integer.toString(x).length() * @ Return numero di cifre in X, ad esempio, Integer.toString (x). Lunghezza ()
* @author Marc Chappuis * @ Autore Marc Chappuis marnic@ludomedia.ch
*/ * /
public static int widthInDigits(int x) { public static int widthInDigits (int x) (
// do an unravelled binary search / / Effettuare una ricerca binaria unravelled
if (x if (x